来自尚硅谷,通用的jdbc工具类
然后使用jdbc工具类写了通用的增删改方法和查方法
mysql驱动
mysql-connector-java-5.1.7-bin.jar
https://download.csdn.net/download/yougcave/19752818
CREATE TABLE `customers` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(15) DEFAULT NULL,
`email` varchar(20) DEFAULT NULL,
`birth` date DEFAULT NULL,
`photo` mediumblob,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=gb2312;
url=jdbc:mysql://localhost:3306/test
user=root
password=333
driverClass=com.mysql.jdbc.Driver
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils {
public static Connection getConnection() throws Exception{
//读取配置文件
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pp = new Properties();
pp.load(in);
String url = pp.getProperty("url");
String user = pp.getProperty("user");
String password = pp.getProperty("password");
String driverClass = pp.getProperty("driverClass");
//加载数据库驱动
Class.forName(driverClass);
//获取连接
java.sql.Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
public static void closeResource(Connection conn, Statement ps){
try {
if (ps != null){
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void closeResource(Connection conn, Statement ps, ResultSet rs){
try {
if (ps != null){
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (rs != null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
import com.atguigu3.util.JDBCUtils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PreparedStatement {
//测试通用类
@Test
public void updateTest() {
String sql = "delete from customers where id = ?";
updateCommon(sql,20);
}
//增删改 通用类
public void updateCommon(String sql, Object ...args) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i+1,args[i]);
}
ps.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn,ps);
}
}
//原始插入数据方法
@Test
public void insertTest() {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JDBCUtils.getConnection();
String sql = "insert into customers(name,email,birth)values(?,?,?)";
ps = conn.prepareStatement(sql);
ps.setObject(1,"苍井空");
ps.setObject(2,"234242@qq.com");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("1000-1-9");
ps.setObject(3,new java.sql.Date(date.getTime()));
ps.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn,ps);
}
}
}
package com.atguigu3.preparedstatement.crud;
import com.atguigu3.util.JDBCUtils;
import org.junit.Test;
import java.lang.reflect.Field;
import java.sql.*;
import java.sql.PreparedStatement;
public class CustomerForQuery {
@Test
public void query(){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Customers customers = null;
try {
conn = JDBCUtils.getConnection();
String sql = "select * from customers where id = ?";
ps = conn.prepareStatement(sql);
ps.setObject(1,1);
rs = ps.executeQuery();
customers = null;
while (rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
String email = rs.getString(3);
Date date = rs.getDate(4);
customers=new Customers(id,name,email,date);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn,ps,rs);
}
System.out.println(customers);
}
@Test
public void queryTest(){
String sql = "select id,name,email from customers where id = ?";
Customers cust = queryCommon(Customers.class, sql, 4);
System.out.println(cust);
}
//获取select的通用方法
public <T> T queryCommon(Class<T> clazz,String sql,Object ...args) {
Connection conn =null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//获取连接
conn = JDBCUtils.getConnection();
//预编译sql语句
ps = conn.prepareStatement(sql);
//赋值,由于不知道类型,用object
for (int i = 0; i < args.length; i++) {
ps.setObject(i+1,args[i]);
}
//获取运行结果
rs = ps.executeQuery();
//获取ps的元数据,元数据里获取列数和列名的方法
ResultSetMetaData rsmd = rs.getMetaData();
//通过元数据来获取数据列数
int columnCount = rsmd.getColumnCount();
if (rs.next()){
T t = clazz.newInstance();
for (int i = 1; i <= columnCount; i++) {
//获取列值,这时候还不知道列名和数据类型
Object colunmValue = rs.getObject(i);
//通过元数据来获取列名 换成别名
//String columnName = rsmd.getColumnName(i);
String columnLabel = metaData.getColumnLabel(i);
//通过反射,用列名来获取列的数据类型
Field field = clazz.getDeclaredField(columnLabel);
//设置可以获取私有方法
field.setAccessible(true);
//把值和属性都赋给对象cust
field.set(t,colunmValue);
}
return t;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn,ps,rs);
}
return null;
}
}
select方法里重点是
1,通过rs的元数据来获取列数量和列名
2,通过反射实体类来获取列属性
import com.atguigu3.util.JDBCUtils;
import org.junit.Test;
import java.io.*;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
public class QueryPhoto9 {
//插入图片到数据库
@Test
public void updateTest(){
Connection conn = null;
PreparedStatement ps = null;
FileInputStream fis = null;
int i = 0;
try {
conn = JDBCUtils.getConnection();
String sql = "insert into customers values(?,?,?,?,?)";
ps = conn.prepareStatement(sql);
//设置参数
ps.setInt(1,31);
ps.setString(2,"java");
ps.setString(3,"234234@qq.com");
//设置时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("1993-02-10");
ps.setDate(4,new java.sql.Date(date.getTime()));
//插入图片,图片放在项目的根目录
fis = new FileInputStream(new File("girl.jpg"));
ps.setBlob(5,fis);
//用executeUpdate代替execute,可以返回一个boolean值
i = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭连接
JDBCUtils.closeResource(conn,ps);
//是流就得关闭
try {
if (fis != null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(i>0?"插入成功":"插入失败");
}
//从数据库中读取图片,读取后的图片放在项目根目录
@Test
public void queryTest(){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
InputStream is = null;
FileOutputStream fos = null;
try {
conn = JDBCUtils.getConnection();
String sql = "select * from customers where id = ?";
ps = conn.prepareStatement(sql);
//设置参数
ps.setInt(1,31);
rs = ps.executeQuery();
//读取结果集
if (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
java.sql.Date birth = rs.getDate("birth");
Blob photo = rs.getBlob("photo");
//前四个数据封装到对象中
Customers cust = new Customers(id, name, email, birth);
System.out.println(cust);
//读取图片,把图片转换成流
is = photo.getBinaryStream();
fos = new FileOutputStream(new File("outgirl9.jpg"));
//流传输
int len;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn,ps,rs);
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos != null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}