我正在使用sqllite
编写java应用程序public Product createProduct(String productName) throws SQLException {
String query = "INSERT into tbl_Product (name) values (?) ";
PreparedStatement preparedStatement = null;
Connection connection = null;
ResultSet rs = null;
Product product = null;
try {
connection = ConnectionFactory.getConnection();
preparedStatement = connection.prepareStatement(query);
//preStatement.setInt(1, 0);
preparedStatement.setString(1, productName);
preparedStatement.executeUpdate();
} finally {
//preparedStatement.close();
DbUtil.close(rs);
DbUtil.close(preparedStatement);
DbUtil.close(connection);
}
return product;
}
我的产品表有(ID,Name)列,其中Id是自动生成的。需要进行所有java更改的内容,以便preStatement可以在db。中插入自动生成的id。
答案 0 :(得分:0)
String query =“INSERT into tbl_Product values(?)”;
ResultSet rs = null;
Product product = null;
try {
connection = ConnectionFactory.getConnection();
preStatement = (PreparedStatement) connection.prepareStatement(query);
preStatement.setString(1, productName);
rs = preStatement.executeQuery();
答案 1 :(得分:0)
String sqlQuery = "INSERT into tbl_Product values (?)
PreparedStatement stmt = conn.prepareStatement(sqlQuery);
stmt.setString( 1, "val" ); //nameText variable contains the text of the jtextfield)
stmt.executeUpdate();
使用执行更新而不是执行查询。
executeQuery()
:
在此PreparedStatement对象中执行SQL查询,并返回查询生成的ResultSet对象。
executeUpdate()
:
在此PreparedStatement对象中执行SQL语句,该对象必须是SQL INSERT,UPDATE或DELETE语句;或者不返回任何内容的SQL语句,例如DDL语句。