java PreparedStatement :一个SQL插入例子

・1 分钟阅读

Java PreparedStatement常见问题解答:能分享一个执行SQL INSERT查询的Java PreparedStatement的例子吗?

下面是一个java/jdbc PreparedStatementINSERT查询例子的源代码:

//
// A simple Java JDBC PreparedStatement example using a SQL INSERT.
//
public void addUser(User user, Connection conn)
throws SQLException
{
 String query =\"INSERT INTO Users (\"
 +\" user_id,\"
 +\" username,\"
 +\" firstname,\"
 +\" lastname,\"
 +\" companyname,\"
 +\" email_addr,\"
 +\" want_privacy ) VALUES (\"
 +\"null, ?, ?, ?, ?, ?, ?)\";
 try {
 // set all the preparedstatement parameters
 PreparedStatement st = conn.prepareStatement(query);
 st.setString(1, user.getName());
 st.setString(2, user.getFirstName());
 st.setString(3, user.getLastName());
 st.setString(4, user.getCompanyName());
 st.setString(5, user.getEmail());
 st.setString(6, user.getPrivacy());
 // execute the preparedstatement insert
 st.executeUpdate();
 st.close();
 } 
 catch (SQLException se)
 {
 // log exception
 throw se;
 }
}

讨论
Xn_warm profile image