首先是连接,关闭资源等数据库操作
将连接数据库,关闭资源封装在JDBCUtils里
package jdbc.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class JDBCUtils { //获取数据库连接函数 public static Connection getConnection() throws Exception { Class clazz=Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String url = "jdbc:sqlserver://localhost:1433;databaseName=EDUCATION"; Connection con = DriverManager.getConnection(url,"sa","1"); System.out.println("连接成功"); return con; } //关闭连接和操作指针 public static void closeResource(Connection con,PreparedStatement ps) { try { if(ps != null) ps.close(); } catch(Exception ex) { ex.printStackTrace(); } try { if(con != null) con.close(); } catch(Exception ex) { ex.printStackTrace(); } } //关闭连接,信使,结果集 public static void closeResource(Connection con,PreparedStatement ps,ResultSet resultSet) { try { if(ps != null) ps.close(); } catch(Exception ex) { ex.printStackTrace(); } try { if(con != null) con.close(); } catch(Exception ex) { ex.printStackTrace(); } try { if(resultSet != null) resultSet.close(); } catch(Exception ex) { ex.printStackTrace(); } } }
使用PreparedStatement对数据库进行单条的增删改等操作以及通用的操作
package jdbc_practice.preparedstatement.crud; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import jdbc.utils.JDBCUtils;; /* * PreparedStatement代替Statement, 实现对数据库增删改 * */ public class PreparedStatementUpdateTest { //增加class的一条记录 public static void testAdd() { Connection con=null; PreparedStatement ps=null; try { con=JDBCUtils.getConnection(); String sql="insert into class values(?,?)"; ps=con.prepareStatement(sql); ps.setObject(1,"030103"); ps.setObject(2, "物联网"); ps.execute(); System.out.println("增加成功"); } catch(Exception ex) { ex.printStackTrace(); } finally { JDBCUtils.closeResource(con, ps); } } //修改class的一条记录 public static void testUpdate(){ Connection con=null; PreparedStatement ps=null; try { con = JDBCUtils.getConnection(); //建立信使ps,预编译sql语句 String sql = "update class set cName = ? where classId = ?"; ps = con.prepareStatement(sql); //填充占位符 ps.setObject(1, "数媒"); ps.setObject(2, "030100"); //执行 ps.execute(); System.out.println("修改成功"); } catch(Exception e) { e.printStackTrace(); } finally { JDBCUtils.closeResource(con, ps); } } //删除class的一条记录 public static void testDelete() { Connection con=null; PreparedStatement ps=null; try { con=JDBCUtils.getConnection(); String sql="delete class where cName=?"; ps=con.prepareStatement(sql); ps.setObject(1,"计科"); ps.execute(); System.out.println("删除成功"); } catch(Exception ex) { ex.printStackTrace(); } finally { JDBCUtils.closeResource(con, ps); } } //通用增删改,参数为预编译的sql,和可变形参args用来充当占位符 public static void update(String sql,Object ...args) { Connection con = null; PreparedStatement ps=null; try { //1.获取连接 con=JDBCUtils.getConnection(); //2.预编译sql,返回ps实例 ps=con.prepareStatement(sql); //填充占位符,sql中的占位符个数=args数组长度 for(int i=0;i<args.length;i++) { ps.setObject(i+1, args[i]); } //4.执行 ps.execute(); System.out.println("执行成功 "); } catch (Exception ex) { ex.printStackTrace(); } finally { //5.关闭资源 JDBCUtils.closeResource(con, ps); } } //对上述三种操作进行测试 public static void main(String []args) { String sql="insert into class values(?,?)"; String s1,s2; s1="030104"; s2="计创"; update(sql,s1,s2); sql="delete from class where cName=?"; s1="计创"; update(sql,s1); sql="update class set cName=? where classId=?"; s1="计创"; s2="030102"; update(sql,s1,s2); } }
使用PreparedStatement对表进行通用查询操作,即查询字段args是个可变参数
package jdbc_practice.preparedstatement.crud; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.lang.reflect.Field; import jdbc.utils.*; import bean.Class; public class ClassforQuery { //对表的通用查询操作:即查询字段是个可变参数 public static Class queryForClass(String sql,Object...args) { Connection con = null; PreparedStatement ps=null; ResultSet res = null; try { con=JDBCUtils.getConnection(); ps=con.prepareStatement(sql); for(int i=0;i<args.length;i++) { ps.setObject(i+1, args[i]); } res=ps.executeQuery(); //获取结果集的元数据 ,元数据指的是每个列的列名,String name = "Tom",String 和name是修饰Tom的元数据 ResultSetMetaData rsmd = res.getMetaData(); //通过rsmd来获取结果集中的列数 int col = rsmd.getColumnCount(); if(res.next()) { Class clazz = new Class(); //处理一行数据中的每一个列 for(int i=0;i<col;i++) { //获取每个列的属性值 Object value = res.getObject(i+1); //获取每个列的列名 String colName = rsmd.getColumnName(i+1); //给clazz对象的colName属性,赋值为value:通过反射 Field field = Class.class.getDeclaredField(colName);//先拿到属性名为colName的属性 field.setAccessible(true);//将属性设置为可访问 field.set(clazz, value);//修改该对象的该属性值为value } System.out.println("执行成功"); return clazz; } } catch(Exception ex) { ex.printStackTrace(); } finally {//finally块在return执行之后,return返回之前执行 JDBCUtils.closeResource(con, ps, res); } return null; } public static void main(String []args) { String sql = "select classId,cName from class where classId = ?"; String arg1 = "030100",arg2 = ""; Class clazz = queryForClass(sql,arg1); System.out.println(clazz); } }
对单表查询的升级,解决了数据库表的列名和java类名不同的情况
package jdbc_practice.preparedstatement.crud; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import bean.Student; import jdbc.utils.JDBCUtils; import java.lang.reflect.Field; public class StudentForQuery { public static Student queryForStudent(String sql,Object...args) { Connection con = null; PreparedStatement ps = null; ResultSet res = null; try { con=JDBCUtils.getConnection(); ps=con.prepareStatement(sql); for(int i=0;i<args.length;i++) { ps.setObject(i+1, args[i]); } //获得数据集和元数据集 res = ps.executeQuery(); ResultSetMetaData rsmd = res.getMetaData(); int col = rsmd.getColumnCount(); if(res.next()) { Student stu = new Student(); for(int i=0;i<col;i++) { Object value = res.getObject(i+1); //要获得的数据值 String colLabel = rsmd.getColumnLabel(i+1); //要获得的元数据名称 Field field = Student.class.getDeclaredField(colLabel);//这里要用Label以解决数据库表类名称和类属性名不同的情况 field.setAccessible(true); field.set(stu,value); } System.out.println("执行成功"); return stu; } } catch(Exception ex) { ex.printStackTrace(); } finally { JDBCUtils.closeResource(con, ps, res); } return null; } public static void main(String[]args) { String sql = "select stuId as studentId,stuName as studentName from student where stuName = ?"; String arg = "李军"; Student stu = queryForStudent(sql,arg); System.out.println(stu); } }
使用PreparedStatement实现对不同表的通用的返回一个对象的查询操作
以及使用ArrayList返回对不同表的通用的返回多个对象的查询操作
package jdbc_practice.preparedstatement.crud; import java.lang.reflect.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.util.ArrayList; import java.util.List; import bean.Student; import jdbc.utils.JDBCUtils; public class PreparedStatementQueryTest { //使用PreparedStatement实现对不同表的通用的返回一个对象的查询操作 //使用泛型机制,参数里先传入一个类的类型 public static <T> T getInstance(Class<T> clazz,String sql,Object...args) { Connection con = null; PreparedStatement ps = null; ResultSet res = null; try { con=JDBCUtils.getConnection(); ps=con.prepareStatement(sql); for(int i=0;i<args.length;i++) { ps.setObject(i+1, args[i]); } //获得数据集和元数据集 res = ps.executeQuery(); ResultSetMetaData rsmd = res.getMetaData(); int col = rsmd.getColumnCount(); if(res.next()) { T t = clazz.newInstance(); for(int i=0;i<col;i++) { Object value = res.getObject(i+1); //要获得的数据值 String colLabel = rsmd.getColumnLabel(i+1); //要获得的元数据名称 //通过反射给t对象指定的colName属性赋值为value Field field = clazz.getDeclaredField(colLabel); field.setAccessible(true); field.set(t,value); } System.out.println("执行成功"); return t; } } catch(Exception ex) { ex.printStackTrace(); } finally { JDBCUtils.closeResource(con, ps, res); } return null; } //返回对不同表的通用的返回多个对象的查询操作 public static <T> ArrayList<T> getForList(Class<T> clazz,String sql,Object...args){ Connection con = null; PreparedStatement ps = null; ResultSet res = null; try { con=JDBCUtils.getConnection(); ps=con.prepareStatement(sql); for(int i=0;i<args.length;i++) { ps.setObject(i+1, args[i]); } //获得数据集和元数据集 res = ps.executeQuery(); ResultSetMetaData rsmd = res.getMetaData(); int col = rsmd.getColumnCount(); ArrayList<T> list = new ArrayList<T>(); while(res.next()) { T t = clazz.newInstance(); for(int i=0;i<col;i++) { Object value = res.getObject(i+1); //要获得的数据值 String colLabel = rsmd.getColumnLabel(i+1); //要获得的元数据名称 //通过反射给t对象指定的colName属性赋值为value Field field = clazz.getDeclaredField(colLabel); field.setAccessible(true); field.set(t,value); } list.add(t); } System.out.println("执行成功"); return list; } catch(Exception ex) { ex.printStackTrace(); } finally { JDBCUtils.closeResource(con, ps, res); } return null; } public static void main(String []args) { String sql = "select stuName as studentName,stuId as studentId from student where stuId = ?"; String arg = "101"; Student stu = getInstance(Student.class,sql,arg); System.out.println(stu); sql = "select stuId as studentId,stuName as studentName from student where stuId > ?"; arg = "0"; ArrayList<Student> list = getForList(Student.class, sql, arg); list.forEach(System.out::println); } }
原文地址:https://www.cnblogs.com/zsben991126/p/11846262.html
时间: 2024-11-10 15:48:59