我必须将数据插入数据库。因为sql语句VALUES(......)有8个参数。是否熟练使用insert语句?
Class UserRegistration {
public void insertToDatabase(){
String sql=" INSERT INTO db1(......) Values(id,fname,lastname,username,password,usertype,email,contact,address )"
}
}
答案 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();
}