<pre name="code" class="java">/*
*
* 演示preparedStatment的使用crud
* preparedstatement可以提高执行效率(因为它有预编译的功能)
* preparedstatement可以防止sql注入,但是要求用?赋值的方式才可以
*/
package com.test;
import java.sql.*;
public class Test2 {
public static void main(String[] args) {
//定义需要的对像
PreparedStatement ps=null;
Connection ct=null;
ResultSet rs=null;
try{
//加载驱动
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//得到连接
ct=DriverManager.getConnection("jdbc:odbc:mytest","sa","199303");
//创建PerparedStatement
ps=ct.prepareStatement("select *from dept where deptno=? and loc=?");
//这样可以防止sql注入的风险
ps.setInt(1, 20);
ps.setString(2, "dallas");
rs=ps.executeQuery();
while(rs.next())
{
int deptno=rs.getInt(1);
String dname=rs.getString(2);
String loc=rs.getString(3);
System.out.println(deptno+" "+dname+" "+loc);
}
}catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
if(rs!=null)
{
rs.close();
}
if(ps!=null)
{
ps.close();
}
if(ct!=null)
{
ct.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
* 演示preparedStatment的使用crud
最新推荐文章于 2019-01-10 17:06:11 发布