这篇文章主要介绍Java之PreparedStatement怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
PreparedStatement介绍
可以通过调用 Connection 对象的 prepareStatement(String sql) 方法获取 PreparedStatement 对象
PreparedStatement 接口是 Statement 的子接口,它表示一条预编译过的 SQL 语句
PreparedStatement 对象所代表的 SQL 语句中的参数用问号(?)来表示(?在SQL中表示占位符),调用 PreparedStatement 对象的 setXxx() 方法来设置这些参数. setXxx() 方法有两个参数,第一个参数是要设置的 SQL 语句中的参数的索引(从 1 开始),第二个是设置的 SQL 语句中的参数的值

PreparedStatement vs Statement
插入案例
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)

执行操作:

package com.atmf;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import org.junit.Test;
public class SumUP {
@Test
public void getConnection() {
Connection con = null;
PreparedStatement ps = null;
try {
//1,加载配置文件
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pr = new Properties();
pr.load(is);
//2,读取配置信息
String user = pr.getProperty("user");
String password = pr.getProperty("password");
String url = pr.getProperty("url");
String driverClass = pr.getProperty("driverClass");
//3.加载驱动
Class.forName(driverClass);
//4,获取连接
con = DriverManager.getConnection(url, user,password);
String sql = "insert into customers(name,birth) value(?,?)";
//预编译sql语句,得到PreparedStatement对象
ps = con.prepareStatement(sql);
//5,填充占位符
ps.setString(1, "三明治");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("2020-11-02");
ps.setDate(2, new java.sql.Date(date.getTime()));
//6,执行操作
ps.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//7,关闭资源
try {
if(ps != null)
ps.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(con != null)
con.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
配置信息:jdbc.properties文件
user=root
password=123456
url=jdbc:mysql://localhost:3306/students
driverClass=com.mysql.jdbc.Driver
执行结果:

以上是“Java之PreparedStatement怎么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注天达云行业资讯频道!