将静态ArrayList中的数据插入mySql数据库中的表中

时间:2013-12-03 22:19:46

标签: java mysql jdbc

提前感谢您的任何建议。我有一个ArrayList并试图输入数据到mysql数据库。我得到的错误: com.mysql.jdbc.MysqlDataTruncation:数据截断:第1行列'Id'的数据太长 我检查了item.id是表中最多2个字符,Id = varchar(3)。我还附上了屏幕截图,以显示表格中元素的大小。当我将ArrayList中的值分配给表时,我怀疑我的代码在循环中有一些错误。我认为在下面给出的类中这部分代码中存在一些错误。

for(Contact item : pDir){
            s.execute("INSERT INTO pDB.Phone_D (Id, First_Name, 
                    Last_Name, Phone_Number) values ('item.id', 'item.firstName', 'item.lastName', 
                    'item.phoneNumber') ");
        }
</pre> </code>


<pre> <code>
public class Contact {


private static ArrayList<Contact> pDir;
private  String id, firstName, lastName, phoneNumber;
String dataSourceName = "pDB";
String dbURL = "jdbc:mysql://localhost:3306/" + dataSourceName;
String result = "";
Connection con = null;
Statement s;

static{
pDirectory = new ArrayList<Contact>();
    Contact c0 = new Contact("1","Maaaaaa","Madreth","111-000-1998");
    Contact c1 = new Contact("2","Dara","Gurde","020-000-1996");
    Contact c2 = new Contact("3","Maaaaaa","Kvalskrooeee","100-111-1998");
    pDir.add(c0);
    pDir.add(c1);
    pDir.add(c2);   
}

public Contact() {
    for(Contact item : pDir) {
         System.out.println(item.id + " " + item.firstName + " " + item.lastName + " " +  
                 item.phoneNumber);
    }
}

public Contact(String id, String firstName, String lastName, String phoneNumber) {  
    this.id =id;
    this.firstName = firstName; 
    this.lastName = lastName; 
    this.phoneNumber = phoneNumber;
}

public String getFirstName() { return firstName;}
public void setFirstName(String firstName) { this.firstName = firstName;}
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public String getId() { return id;}
public void setId(String id) {this.id = id;}
    public String getPhoneNumber() { return phoneNumber;}
    public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber;}

public Response getLocationDetails(         
    try {
        try{
        Class.forName("com.mysql.jdbc.Driver");
        con = (Connection) DriverManager.getConnection(dbURL,"root","password");
        System.out.println("We are connected to database");
        }
        catch(Exception e) {
        System.out.println("Can not connect to database");
        e.printStackTrace();
        }

                s = (Statement) con.createStatement();
        for(Contact item : pDir){
            s.execute("INSERT INTO pDB.Phone_D (Id, First_Name, 
                    Last_Name, Phone_Number) values ('item.id', 'item.firstName', 'item.lastName', 
                    'item.phoneNumber') ");
        }
         }
}

tablePhone_D

的屏幕截图

enter image description here

1 个答案:

答案 0 :(得分:1)

'item.id'查询(和其他值)中将'"+item.id+"'更改为INSERT
此外,我建议您改为使用PreparedStatement