JDBC_PreparedStatement使用
和 Statement一样,PreparedStatement也是用来执行sql语句的
与创建Statement不同的是,需要根据sql语句创建PreparedStatement
除此之外,还能能够通过设置参数,指定相应的值,而不是Statement那样使用字符串拼接
Statement 需要进行字符串拼接,可读性和维护性比较差
PreparedStatement 使用参数设置,可读性好,不易犯错
import java.sql.*;
public class JDBC_PreparedStatement {
public static void main(String[] args) {
try {
Class.forName(“com.mysql.jdbc.Driver”);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//sql语句的“值”部分,可直接用?代替
String sql = “insert into user values(NULL ,?,?)”;
String sql2 = “update user set name=?, password=? where id=?”;
try (Connection c = DriverManager.getConnection
(“jdbc:mysql://127.0.0.1:3306/mybase?characterEncoding=UTF-8″
,”root”,”614″); Statement s = c.createStatement();
//通过sql语句给PreparedStatement赋值
PreparedStatement preparedStatement =
c.prepareStatement(sql2,Statement.RETURN_GENERATED_KEYS);)
{
//在PreparedStatement的set方法中(第一个是指定哪个? 顺序排列,第二个参数是赋给此?哪个值)
preparedStatement.setString(1, “dasha”);
preparedStatement.setString(2, “thisispassword4”);
preparedStatement.setInt(3,4);
preparedStatement.execute();
ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
while (generatedKeys.next()){
System.out.println(generatedKeys.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}