简体   繁体   English

如何将 ArrayList 数据插入数据库

[英]How to Insert ArrayList data to the DataBase

Im try to insert data into Database using ArrayList.there is a Erro msg.我尝试使用 ArrayList 将数据插入数据库。有错误消息。 That is my Custmer.class method.那是我的 Custmer.class 方法。 this is what i got from when i going to pass ArrayList into another class.这是我将 ArrayList 传递给另一个 class 时得到的结果。

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

I want to know how to do this using correct Using OOP concept我想知道如何使用正确的 Using OOP 概念来做到这一点

   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:这是我的 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) .在您的 passingMsg() 方法中,您将其 header 作为: 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)) .但是,在您的“我如何从用户获取值”区域(我现在将其称为“第二个代码段”)内,您将方法调用声明为: 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.这意味着您暗示要传递的参数(在本例中为arrInq )是ArrayList<Inquiries>类型,但事实并非如此。 It's being initialized in your 2nd Snippet as: ArrayList<String> arrInq = new ArrayList<String>();它在您的第二个代码段中被初始化为: 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.您还可能希望将方法 header 更改为返回 boolean,或者稍微修复它以实际抛出异常。 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 . 您为ArrayList使用了错误的类型参数。 Instead of ArrayList<String> you need ArrayList<Inquiries> . 代替ArrayList<String>您需要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. 让我们以OOP的方式进行讨论。 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: 例如,我有一个模型“ Model”,它通常映射到数据库表,称它为“ TableModel”,我会做这样的事情:

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: 假设我有一个Model对象列表,并且希望将它们插入数据库中,我将执行以下操作:

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.....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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