package com.getconn;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCUtils {
public static Connection getConnection() throws Exception{
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(in);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
//加载驱动
Class.forName(driverClass);
//获取连接
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
}
public static void closeResource(Connection conn, PreparedStatement ps){
//关闭资源
try{
if(ps != null)
ps.close();
}catch(SQLException e){
e.printStackTrace();
}
try{
if(conn != null)
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
import信息:
package com.hai;
import com.getconn.JDBCUtils;
import org.junit.Test;
import java.sql.*;
import java.text.SimpleDateFormat;
@Test
public void testInsert() throws Exception{
//获取数据库连接
Connection con = JDBCUtils.getConnection();
//预编译sql语言,返回PreparedStatement实例
String sql = "insert into customer(ID,name,email,birth) values(?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
//填充占位符
ps.setInt(1,12);
ps.setString(2,"zhouwang");
ps.setString(3,"[email protected]");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = sdf.parse("1000-01-01");
ps.setDate(4,new Date(date.getTime()));
//执行操作
ps.execute();
//关闭资源
JDBCUtils.closeResource(con,ps);
}
//修改customer表的一条记录
@Test
public void testUpdate(){
Connection conn = null;
PreparedStatement ps = null;
try{
//1.获取数据库连接
conn = JDBCUtils.getConnection();
//2.预编译sql语言,返回PreparedStatement实例
String sql = "update customer set name = ? where id = ?";
ps = conn.prepareStatement(sql);
//3.填充占位符
ps.setString(1,"xianwang");
ps.setInt(2,12);
//4.执行
ps.execute();
}catch(Exception e){
e.printStackTrace();
}finally {
//5.关闭资源
JDBCUtils.closeResource(conn,ps);
}
}
//通用的增删改操作
public void update(String sql,Object ...args){
Connection con = null;
PreparedStatement ps = null;
try{
//1.获取数据库连接
con = JDBCUtils.getConnection();
//2.预编译sql语言,返回PreparedStatement的实例
ps = con.prepareStatement(sql);
//3.填充占位符
for (int i = 0; i < args.length; i++){
ps.setObject(i + 1, args[i]);
}
//4.执行
ps.execute();
}catch (Exception e){
e.printStackTrace();
}finally{
JDBCUtils.closeResource(con,ps);
}
}
@Test
public void testCommonUpdate(){
// String sql = "delete from customer where id = ?";
// update(sql,3);
// String sql = "update `order` set order_name = ? where order_id = ?";//由于order是关键字,所以用``包裹
// update(sql,"DD","2");
String sql_3 = "insert into `order`(order_id,order_name) values(?,?)";
update(sql_3,"001","A");
}
@Test
public void testQuery1() {
Connection conn = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
conn = JDBCUtils.getConnection();
String sql = "select * from customer where id = 12";
ps = conn.prepareStatement(sql);
//执行,并返回结果集
resultSet = ps.executeQuery();
if (resultSet.next()) {//判断结果集的下一条是否有数据,如果有数据返回true,并且指针下移,如果返回false,不指向下一条数据
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
String email = resultSet.getString(3);
Date birth = resultSet.getDate(4);
Customer customer = new Customer(id, name, email, birth);
System.out.println(customer);
}
}catch(Exception e){
e.printStackTrace();
}finally {
//关闭资源
JDBCUtils.closeResource(conn,ps,resultSet);
}
}
//针对customer表的通用查询操作
public Customer queryForCustomer(String sql,Object ...args){
Connection conn = null;
PreparedStatement ps = null;
ResultSet re = null;
try{
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
//填充占位符
for(int i = 0; i < args.length;i++){
ps.setObject(i + 1, args[i]);
}
re = ps.executeQuery();
//获取结果集的元数据:ResultSetMetaData
ResultSetMetaData rsmd = re.getMetaData();
//通过ResultSetMetaData获取结果集中的列数
int columnCount = rsmd.getColumnCount();
if(re.next()){
Customer cust = new Customer();
//处理结果集一行数据中的每一列
for(int i = 0; i < columnCount;i++){
//获取列值
Object columnvalue = re.getObject(i + 1);
//获取每个列的列名:getColumnName()
//获取每个列的别名:getColumnLabel()
String columnName = rsmd.getColumnName(i+1);
//System.out.println(columnName);
//给cust对象指定的columnName属性,赋值为columnvalue,通过反射
Field field = Customer.class.getDeclaredField(columnName);
field.setAccessible(true);
field.set(cust,columnvalue);
}
return cust;
}
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.closeResource(conn,ps,re);
}
return null;
}
@Test
public void testQueryForCustomer() {
String sql = "select ID,name,birth,email from customer where ID = ?";
Customer customer = queryForCustomer(sql, 12);
System.out.println(customer);
}
获取每个列的列名:getColumnName()
获取每个列的别名:getColumnLabel()
//针对Order表的通用查询
public Order queryForOrder(String sql, Object...args){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
//获取结果集的元数据:ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
//通过ResultSetMetaData获取结果集中的列数
int columnCount = rsmd.getColumnCount();
if (rs.next()){
Order order = new Order();
//处理结果集一行数据中的每一列
for (int i = 0; i < columnCount; i++) {
//获取列值
Object columnValue = rs.getObject(i + 1);
//获取每个列的别名
String columnLabel = rsmd.getColumnLabel(i + 1);
//给cust对象指定的columnName属性,赋值为columnvalue,通过反射
Field field = Order.class.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(order,columnValue);
}
return order;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn,ps,rs);
}
return null;
}
@Test
public void testOrderForQuery(){
String sql = "select order_id orderId, order_name orderName, order_date orderDate from `order` where order_id = ?";
Order order = queryForOrder(sql, 1);
System.out.println(order);
}
//针对不同表的通用的查询,返回表中的一条记录
public <T> T getInstance(Class<T> clazz, String sql, Object...args){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
//获取结果集的元数据:ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
//通过ResultSetMetaData获取结果集中的列数
int columnCount = rsmd.getColumnCount();
if (rs.next()){
T t = clazz.newInstance();
//处理结果集一行数据中的每一列
for (int i = 0; i < columnCount; i++) {
//获取列值
Object columnValue = rs.getObject(i + 1);
//获取每个列的别名
String columnLabel = rsmd.getColumnLabel(i + 1);
//给cust对象指定的columnName属性,赋值为columnvalue,通过反射
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t,columnValue);
}
return t;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn,ps,rs);
}
return null;
}
@Test
public void testGetInstance(){
String sql = "select order_id orderId, order_name orderName, order_date orderDate from `order` where order_id = ?";
Order order = getInstance(Order.class, sql, 1);
System.out.println(order);
}
public <T> List<T> getForList(Class<T> clazz, String sql, Object...args){
ArrayList<T> list = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
//获取结果集的元数据:ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
//通过ResultSetMetaData获取结果集中的列数
int columnCount = rsmd.getColumnCount();
//创建集合对象
list = new ArrayList<>();
while (rs.next()){
T t = clazz.newInstance();
//处理结果集一行数据中的每一列:给对象指定属性赋值
for (int i = 0; i < columnCount; i++) {
//获取列值
Object columnValue = rs.getObject(i + 1);
//获取每个列的别名
String columnLabel = rsmd.getColumnLabel(i + 1);
//给cust对象指定的columnName属性,赋值为columnvalue,通过反射
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t,columnValue);
}
list.add(t);
}
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn,ps,rs);
}
return null;
}
@Test
public void testGetForList(){
String sql = "select id, name, email from `customers` where id < ?";
List<Customer> list = getForList(Customer.class, sql, 12);
list.forEach(System.out::println);
}
参考视频地址