赞
踩
一.创建数据库连接和关闭资源
二.创建javaBean,用来将数据库中查询到的结果通过映射封装成对象
三.数据的查询操作
四.数据库的更新操作
五.将代码封装在测试类中并完成测试
美好的一天从白嫖开始
一.创建数据库连接和关闭资源
package com.jdbc.JDBCUtil; import java.sql.*; public class JDBCUtils { /** * 获取数据库连接 * @return 返回数据库连接对象 * @throws Exception */ public static Connection getConnection() throws Exception { //1,注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/jdbc_db"; String user = "root"; String password = "3.141592654"; //获取数据连接对象 Connection conn = DriverManager.getConnection(url, user, password); return conn; } /** * 关闭流的操作 * @param conn * @param st */ public static void closeResource(Connection conn, Statement st){ try { if (conn != null){ conn.close(); } if (st != null){ st.close(); } } catch (SQLException e) { e.printStackTrace(); } } public static void closeResource(Connection conn, Statement st, ResultSet res){ try { if (conn != null){ conn.close(); } if (st != null){ st.close(); } if (res != null){ res.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
二.创建javaBean,用来将数据库中查询到的结果通过映射封装成对象
package com.jdbc.bean; public class User { private int userId; private String userName; public User() { } public User(int id, String name) { this.userId = id; this.userName = name; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Override public String toString() { return "User{" + "id=" + userId + ", name='" + userName + '\'' + '}'; } }
三.数据的查询操作
package com.jdbc.connection; import com.jdbc.JDBCUtil.JDBCUtils; import com.jdbc.bean.User; import com.sun.java.accessibility.util.EventID; import jdk.nashorn.internal.scripts.JD; import org.junit.Test; import javax.sql.rowset.JdbcRowSet; import java.lang.reflect.Field; 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 static com.jdbc.JDBCUtil.JDBCUtils.*; public class PrepareStatementTest { @Test public void testSelectTab() throws Exception { String sql = "select id userId,name userName from user_tab"; List<User> userList = selectManyInfo(User.class, sql); //拉姆达表达式 userList.forEach(System.out::println); } @Test public void testSelectAnyTab() throws Exception { String sql = "select id userId,name userName from user_tab where id = ?"; User user = selectinfo(User.class, sql, 103); System.out.println(user); } @Test public void testUpdate(){ String sql = "update user_tab set name = ? where id = ?"; update(sql,"诸葛亮",102); } /** * 通行的方法实现增删改 * @param sql 增删改语句 * @param args 占位符?个数不一定,根据sql占位符的个数,传入对应数量object */ public static int update(String sql,Object... args){ int temp = -1; Connection conn = null; PreparedStatement pst = null; try{ //1.获取数据库连接 conn = getConnection(); //2.预编译sql语句 pst = conn.prepareStatement(sql); //3.填充占位符 for (int i = 0; i < args.length; i++) { pst.setObject(i+1,args[i]); } //4.执行 /* pst.execute();如果是查询操作返回的是true 如果是更新操作返回的是false; pst.executeUpdate();返回执行操作以后受影响的行数 */ // pst.execute(); temp = pst.executeUpdate(); }catch (Exception e){ e.printStackTrace(); }finally { //5.释放资源 closeResource(conn,pst); } return temp; } /** * 查询一条记录 * @param tClass 表对应的类对象 * @param sql 查询语句 * @param args 占位符,个数不定 * @param <T> 泛型 * @return 将查询的结果封装一个对象并返回 * @throws Exception */ public static <T> T selectinfo(Class<T> tClass, String sql, Object... args) throws Exception { Connection conn = null; PreparedStatement pst = null; ResultSet res = null; try{ //获取数据库连接 conn = getConnection(); //预编译sql语句 pst = conn.prepareStatement(sql); for (int i = 0; i < args.length; i++) { pst.setObject(i+1,args[i]); } //执行sql语句 res = pst.executeQuery(); //获取结果集的元数据 ResultSetMetaData metaData = res.getMetaData(); //获取结果集列数 int colCount = metaData.getColumnCount(); //处理查询结果集 if (res.next()){ T t = tClass.newInstance();//利用反射来创建对象,newInstance()公共方法,每个类都要求实现 for (int i = 0; i < colCount; i++) { //获取列值,列名 Object colValue = res.getObject(i+1); String colLabel = metaData.getColumnLabel(i+1); //利用反射机制来找到对应的类 Field field = tClass.getDeclaredField(colLabel); field.setAccessible(true); field.set(t,colValue); } return t; } }catch (Exception e){ e.printStackTrace(); }finally { JDBCUtils.closeResource(conn,pst,res); } return null; } /** * 查询多条记录 * @param tClass * @param sql * @param args * @param <T> * @return */ public static <T> List<T> selectManyInfo(Class<T> tClass, String sql, Object... args){ Connection conn = null; PreparedStatement pst = null; ResultSet res = null; List<T> list = new ArrayList<>(); try { //获取数据库连接对象 conn = getConnection(); //预编译sql语句 pst = conn.prepareStatement(sql); //填充占位符 for (int i = 0; i < args.length; i++) { pst.setObject(i+1,args[i]); } //执行sql语句 res = pst.executeQuery(); //获取res的元数据,查看结果集有几列 ResultSetMetaData metaData = res.getMetaData(); int colCount = metaData.getColumnCount(); //处理查询结果集 while (res.next()){//当res不为空时,将res指针下移,并都其中的数据 T t = tClass.newInstance(); for (int i = 0; i < colCount; i++) { //获取列名 String colName = metaData.getColumnLabel(i + 1); //获取列值 Object colValue = res.getObject(i + 1); //利用反射机制创建对象 //将获取到的列名映射User类中相应的属性上 Field field = User.class.getDeclaredField(colName); //将该属性设置为可读 field.setAccessible(true); ## 总结 这个月马上就又要过去了,还在找工作的小伙伴要做好准备了,小编整理了大厂java程序员面试涉及到的绝大部分**面试题及答案**,希望能帮助到大家 ![在这里插入图片描述](https://img-blog.csdnimg.cn/img_convert/19bdb5dbaf094dd02dd89fba6b2ae4ef.webp?x-oss-process=image/format,png) ![在这里插入图片描述](https://img-blog.csdnimg.cn/img_convert/53da22593fdf5dc69e79aabdeb4b6537.webp?x-oss-process=image/format,png) //获取列名 String colName = metaData.getColumnLabel(i + 1); //获取列值 Object colValue = res.getObject(i + 1); //利用反射机制创建对象 //将获取到的列名映射User类中相应的属性上 Field field = User.class.getDeclaredField(colName); //将该属性设置为可读 field.setAccessible(true); ## 总结 这个月马上就又要过去了,还在找工作的小伙伴要做好准备了,小编整理了大厂java程序员面试涉及到的绝大部分**面试题及答案**,希望能帮助到大家 [外链图片转存中...(img-teOCb0lr-1714319655605)] [外链图片转存中...(img-jbYyANY0-1714319655606)] > **本文已被[CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】](https://bbs.csdn.net/topics/618154847)收录**
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。