PreparedStatement 的优点
在JDBC应用中,如果你已经是稍有水平开发者,你就应该始终以PreparedStatement代替Statement.也就是说,在任何时候都不要使用Statement.
- 虽然用PreparedStatement来代替Statement会使代码多出几行,但这样的代码无论从可读性还是可维护性上来说.都比直接用Statement的代码高很多档次
- .PreparedStatement尽最大可能提高性能
- 最重要的一点是极大地提高了安全性.
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//useUnicode=true&characterEncoding=UTF-8 解决中文乱码
String url = "jdbc:mysql://localhost:3306/test?user=root&password=&useUnicode=true&characterEncoding=UTF-8";
String username = "root";
String password = "123456";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url,username,password);
//3.编写SQL
String sql = "insert into users(id,name,password,email,birthday) values (?,?,?,?,?)";
//预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,4);//给第一个占位符?赋值为1
preparedStatement.setString(2,"Krito");//给第二个占位符?赋值为Krito
preparedStatement.setString(3,"123456");
preparedStatement.setString(4,"[email protected]");
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));
//5.执行SQL,返回一个ResultSet:结果集
int i = preparedStatement.executeUpdate();
if(i<0)
{
System.out.println("输入成功");
}
//6.关闭连接:释放资源(一定要做)先开后关
preparedStatement.close();
connection.close();
}
//增删改都用executeUpdate,查找用executeQuery
```