PreparedStatement(从Statement继承):用于执行带或不带参数的预编译SQL语句;
/**
* PreparedStatement基本用法
*/
public class Demo03 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
//加载驱动类
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
String sql = "insert into t_user(id,username,pswd) values (?,?,?)";//?占位符
ps = conn.prepareStatement(sql);
// ps.setInt(1, 1005);//参数索引从1开始
// ps.setString(2, "王五");
// ps.setString(3, "5555");
ps.setObject(1, 1006);
ps.setObject(2, "赵六");
ps.setObject(3, "6666");
ps.execute();
System.out.println("插入了一行记录");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}