简体   繁体   中英

How to Insert ArrayList data to the DataBase

Im try to insert data into Database using ArrayList.there is a Erro msg. That is my Custmer.class method. this is what i got from when i going to pass ArrayList into another class.

incompatible types: ArrayList<String> cannot be converted to ArrayList<Inquiries>

I want to know how to do this using correct Using OOP concept

   public void passingMsg(ArrayList<Inquiries> arrlist){
        try {
            System.out.println("Method "+arrlist);
            String sq = "INSERT INTO Inquiries (name,mail,tp,msg)VALUES(?,?,?)";
            PreparedStatement pr = con.prepareStatement(sq);
            for(int i=0;i<arrlist.size();i++){
                pr.setString(1,arrlist.get(i).getName());
                pr.setString(2,arrlist.get(i).getMail());
                pr.setString(3,arrlist.get(i).getTp());
                pr.setString(4,arrlist.get(i).getMsg());


            }
            pr.executeQuery();//executeBatch();
        } catch (SQLException ex) {
        }

    }

and this is how i get values from user

 String name = txtName.getText();
        String mail = txtEmail.getText();
        String tp = txtTp.getText();
        String msg = txtMsg.getText();

        ArrayList<String> arrInq = new ArrayList<String>();
        arrInq.add(name);
        arrInq.add(mail);
        arrInq.add(tp);
        arrInq.add(msg);


        Custmer c =new Custmer();
        if( c.passingMsg(arrInq)){
            try {
                JOptionPane.showMessageDialog(this, "Successs!!");
            } catch (Exception e) {
                 JOptionPane.showMessageDialog(this, "Unsuccesss!!");
                e.printStackTrace();
            }
        }

and this is my Inquiries.class:

public class Inquiries {
    private String name;
    private String mail;
    private String tp;
    private String msg;


     public Inquiries(String name,String mail,String tp,String msg){
        this.name = name;
        this.mail = mail;
        this.tp = tp;
        this.msg = msg;
    }
//     
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMail() {
        return mail;
    }
    public void setMail(String mail) {
        this.mail = mail;
    }
    public String getTp() {
        return tp;
    }
    public void setTp(String tp) {
        this.tp = tp;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }

}

Can Some one please explain whats wrong with this. please?

Reason For Error

This was simply telling you that your types were incompatible for the operation you were trying to perform. In your passingMsg() method, you have its header as: public void passingMsg(ArrayList<Inquiries> arrlist) . However, inside your "how i get values from user" area, which I will now refer to as "2nd Snippet", you have your method call declared as: if( c.passingMsg(arrInq)) . This means that you are implying that your parameter being passed, arrInq in this case, is of the type ArrayList<Inquiries> , but it's not. It's being initialized in your 2nd Snippet as: ArrayList<String> arrInq = new ArrayList<String>();

Simple Fix

I take no responsibility for this code; use at your own risk. To fix this, you would want to change that entire 2nd Snippet to something similar to the following:

String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));
Custmer c = new Custmer();
try {
    c.passingMsg(arrInq);
    JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
    JOptionPane.showMessageDialog(this, "Unsuccesss!!");
    e.printStackTrace();
}

You would also want to change the method header to either return a boolean, or fix it up a little bit to actually throw the exception. Such as:

public void passingMsg(ArrayList<Inquiries> arrlist) {
    System.out.println("Method " + arrlist);
    String sq = "INSERT INTO Inquiries(name,mail,tp,msg) VALUES(?,?,?)";
    PreparedStatement pr = con.prepareStatement(sq);
    for (Inquiries inquiries : arrlist) {
        pr.setString(1, inquiries.getName());
        pr.setString(2, inquiries.getMail());
        pr.setString(3, inquiries.getTp());
        pr.setString(4, inquiries.getMsg());
    }
    pr.executeQuery();//executeBatch();
}

You are using the wrong type parameter for the ArrayList . Instead of ArrayList<String> you need ArrayList<Inquiries> . To fix the problem, you should remove this code ...

    ArrayList<String> arrInq = new ArrayList<String>();
    arrInq.add(name);
    arrInq.add(mail);
    arrInq.add(tp);
    arrInq.add(msg);

... and replace it with this code:

    ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
    arrInq.add(new Inquiries(name, mail, tp, msg));

Let's talk in OOP way. Here Inquiries is your model, model is nothing but simple class that has instance members and public methods to get and set value of model's instance variable.

Generally we put all database related operations code in their respective models. eg I have model "Model" which typically maps to database table say it as "TableModel" ,I would do something like this:

public class Model{
    private int id;
    private String attr;
    //other properties of the model

    public int getId(){
      return id;
    }
    public void setId(int id){
      this.id=id;
    }
    //other getters and setters

    //here we write methods to performs database operations 
    public void save(){
        //use "this" to get properties of object
        //logic to save to this object in database table TableModel as record
    }
    public void delete(int id){
        //logic to delete this object i.e. from database table TableModel 
    }
    public Model get(int id){
       //retrieve record   from table TableModel with this id
    }
   //other methods to get data from database.
}

Now question is how I can use this in some another class. Let's say I have list of Model objects and I wish to insert them in to database.I will do it something like this:

public class AnotherClass{
    public void someMethod(){
        //create list of models objects e.g. get them from user interface
       ArrayList<Model> models=new ArrayList<>();
       for(int i=0;i<3;i++){
            Model model=new Model();
            model.setId(i);
            model.setAttr("attr"+i);
            models.add(model);
       }
       SomeOtherClass obj=new SomeOtherClass();
       obj.insert(models);
    }
}

public class SomeOtherClass{
   //other code above.....

   //my method that inserts each Model object in database
   //Note: this is sample method , you should do it in optimized way
   // e.g. batch insert
    public void insert(ArrayList<Model> models){

      for(Model myModel:models){
          myModel.save();
      }

   }
   //other code below.....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM