首先了解Statement和PreparedStatement的区别:
由此可见,一般使用PreparedStatement。
操作数据库SU(Course表),其中Course属性有Cno,Cname,Cpno,Ccredit。
publicclassDemo_2 {
publicstaticvoidmain(String[] args) {
PreparedStatement ps=null;
ResultSet rs=null;
Connection ct=null;
try{
//1.加载驱动
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//2.得到连接
ct=DriverManager.getConnection("jdbc:odbc:mytest");
//3.创建PreparedStatement
ps=ct.prepareStatement("select * from Course where Cno=? and Cpno=?");
ps.setString(1,"3"); //给第一个问号赋值
ps.setInt(2,1);
rs=ps.executeQuery();
while(rs.next()){
String Cno=rs.getString(1);
String Cname=rs.getString(2);
intCpno=rs.getInt(3);
intCcredit=rs.getInt(4);
System.out.println(Cno+" "+Cname+" "+Cpno+" "+Ccredit);
}
//使用 PreparedStatement添加一条记录
// ps=ct.prepareStatement("insert into Course values(?,?,?,?)");
// ps.setString(1, "8");
// ps.setString(2, "C++");
// ps.setInt(3, 3);
// ps.setInt(4, 2);
// //执行
// int i=ps.executeUpdate();
// if(i==1){
// System.out.print("添加成功");
// }else{
// System.out.print("添加不成功");
// }
}catch(Exception e) {
e.printStackTrace();
}finally{
try{
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(ct!=null){
ct.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
运行程序,控制台输出符合条件的数据。
最后总结如下:
PreparedStatement 使用crud
1. PreparedStatement可以提高执行的效率(因为它有预编译的功能)
2. PreparedStatement可以防止sql注入,但是要求?赋值的方式才可以。
原神祈愿模拟器最新版
原神祈愿模拟器手机版是一款完整汉化的趣味原神抽卡模拟小游戏,
宝宝森林美食完整版
宝宝森林美食游戏最新版是一款十分有趣的休闲益智游戏,帮助宝宝
g沙盒仇恨官方英文版(gorebox)
G沙盒仇恨英文原版是一款最近非常火热的沙盒模拟类游戏,在这里
迷你世界测试服最新版2024
迷你世界测试服2021最新版,即迷你世界的先遣服版本,用户能
闪耀暖暖最新版2024
闪耀暖暖手游这是非常好玩的换装手游,游戏内容丰富有趣,游戏环