发布时间:2025-12-10 23:05:13 浏览次数:1
可以通过调用 Connection 对象的 prepareStatement(String sql) 方法获取 PreparedStatement 对象
PreparedStatement 接口是 Statement 的子接口,它表示一条预编译过的 SQL 语句
PreparedStatement 对象所代表的 SQL 语句中的参数用问号(?)来表示(?在SQL中表示占位符),调用 PreparedStatement 对象的 setXxx() 方法来设置这些参数. setXxx() 方法有两个参数,第一个参数是要设置的 SQL 语句中的参数的索引(从 1 开始),第二个是设置的 SQL 语句中的参数的值
代码的可读性和可维护性。
PreparedStatement 能最大可能提高性能:
DBServer会对预编译语句提供性能优化。因为预编译语句有可能被重复调用,所以语句在被DBServer的编译器编译后的执行代码被缓存下来,那么下次调用时只要是相同的预编译语句就不需要编译,只要将参数直接传入编译过的语句执行代码中就会得到执行。
在statement语句中,即使是相同操作但因为数据内容不一样,所以整个语句本身不能匹配,没有缓存语句的意义.事实是没有数据库会对普通语句编译后的执行代码缓存。这样每执行一次都要对传入的语句编译一次。
(语法检查,语义检查,翻译成二进制命令,缓存)
PreparedStatement 可以防止 SQL 注入
PreparedStatement常用的方法:
void setObject(int parameterIndex, Object x, int targetSqlType)
parameterIndex the first parameter is 1, the second is 2, …占位符参数索引是从1开始的
其余也是如此:
void setInt(int parameterIndex, int x)
void setLong(int parameterIndex, long x)
void setString(int parameterIndex, String x)
void setBlob (int parameterIndex, Blob x)
void setDate(int parameterIndex, java.sql.Date x, Calendar cal)
执行操作:
packagecom.atmf;importjava.io.IOException;importjava.io.InputStream;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.SQLException;importjava.text.SimpleDateFormat;importjava.util.Date;importjava.util.Properties;importorg.junit.Test;publicclassSumUP{@TestpublicvoidgetConnection(){Connectioncon=null;PreparedStatementps=null;try{//1,加载配置文件InputStreamis=ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");Propertiespr=newProperties();pr.load(is);//2,读取配置信息Stringuser=pr.getProperty("user");Stringpassword=pr.getProperty("password");Stringurl=pr.getProperty("url");StringdriverClass=pr.getProperty("driverClass");//3.加载驱动Class.forName(driverClass);//4,获取连接con=DriverManager.getConnection(url,user,password);Stringsql="insertintocustomers(name,birth)value(?,?)";//预编译sql语句,得到PreparedStatement对象ps=con.prepareStatement(sql);//5,填充占位符ps.setString(1,"三明治");SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd");Datedate=sdf.parse("2020-11-02");ps.setDate(2,newjava.sql.Date(date.getTime()));//6,执行操作ps.execute();}catch(Exceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}finally{//7,关闭资源try{if(ps!=null)ps.close();}catch(Exceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}try{if(con!=null)con.close();}catch(Exceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}}}配置信息:jdbc.properties文件
user=root
password=123456
url=jdbc:mysql://localhost:3306/students
driverClass=com.mysql.jdbc.Driver
执行结果: