插入到具有大量参数的数据库中

时间:2016-09-17 16:40:06

标签: java sql

我必须将数据插入数据库。因为sql语句VALUES(......)有8个参数。是否熟练使用insert语句?

    Class UserRegistration {
public void insertToDatabase(){
       String sql=" INSERT INTO db1(......) Values(id,fname,lastname,username,password,usertype,email,contact,address )"
}


}

1 个答案:

答案 0 :(得分:5)

假设您正在使用JDBC,在Java中执行此操作的正确方法是使用PreparedStatement

String sql = "INSERT INTO db1" +
            " (id,fname,lastname,username,password,usertype,email,contact,address)" +
            " VALUES (?,?,?,?,?,?,?,?,?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
    stmt.setInt   (1, id);
    stmt.setString(2, fname);
    stmt.setString(3, lastname);
    stmt.setString(4, username);
    stmt.setString(5, password);
    stmt.setString(6, usertype);
    stmt.setString(7, email);
    stmt.setString(8, contact);
    stmt.setString(9, address);
    stmt.executeUpdate();
}