当前位置:   article > 正文

java连接mysql增删改查(06通用增删改)

java连接mysql增删改查(06通用增删改)

00.创建数据库

  1. // 1)、创建数据库
  2. CREATE DATABASE jdbc DEFAULT CHARACTER SET UTF8;
  3. // 2)、切换数据库
  4. USE jdbc;
  5. // 3)、创建数据库表
  6. CREATE TABLE user(
  7. `user_id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT '主键',
  8. `user_name` VARCHAR(20) NOT NULL COMMENT '用户名',
  9. `price` double(10,2) DEFAULT 0.0 COMMENT '价格',
  10. `create_time` DATETIME DEFAULT NULL COMMENT '创建时间'
  11. )ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=UTF8 COMMENT="用户表";
  12. // 4)、插入用户
  13. INSERT INTO user(user_name,price,create_time)VALUES('admin',100.12,now());

 01.在src目录下创建配置文件db.properties

  1. jdbc_url=jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8
  2. jdbc_user=root
  3. jdbc_passwd=root

02.创建工具类JdbcUtil3.java

  1. package com.detian;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.SQLException;
  7. import java.util.Properties;
  8. public class JdbcUtil3 {
  9. private static String JDBC_URL=null;
  10. private static String USER_NAME=null;
  11. private static String PASSWORD=null;
  12. //装我们的连接
  13. private static ThreadLocal<Connection> pool = new ThreadLocal<Connection>();
  14. //静态代码块
  15. static {
  16. //加载外部属性资源文件
  17. Properties p = new Properties();
  18. //类加载器
  19. InputStream in = JdbcUtil3.class.getClassLoader().getSystemResourceAsStream("db.properties");
  20. try {
  21. p.load(in);
  22. JDBC_URL = p.getProperty("jdbc_url");
  23. USER_NAME = p.getProperty("jdbc_user");
  24. PASSWORD = p.getProperty("jdbc_passwd");
  25. } catch (IOException e) {
  26. // TODO Auto-generated catch block
  27. e.printStackTrace();
  28. }
  29. }
  30. //获取连接
  31. public static Connection getConnection() throws ClassNotFoundException, SQLException {
  32. Connection connection = pool.get();
  33. if(connection==null) {
  34. Class.forName("com.mysql.jdbc.Driver");
  35. connection = DriverManager.getConnection(JDBC_URL, USER_NAME, PASSWORD);
  36. pool.set(connection);
  37. }
  38. return connection;
  39. }
  40. //关闭连接
  41. public static void close() {
  42. Connection connection = pool.get();
  43. if(connection!=null) {
  44. try {
  45. connection.close();
  46. } catch (SQLException e) {
  47. // TODO Auto-generated catch block
  48. e.printStackTrace();
  49. }
  50. }
  51. //移除此线程局部变量当前线程值
  52. pool.remove();
  53. }
  54. }

03.创建文件BaseDao.java

  1. package com.detian;
  2. import java.lang.reflect.Field;
  3. import java.sql.Connection;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.ResultSetMetaData;
  7. import java.sql.SQLException;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. /**
  11. * 通用数据库操作类
  12. * CRUD(增删改查) SELECT INSERT DELETE UPDATE
  13. * @author 63516
  14. * @param<T> Java端数据类型
  15. * T 代表着java类型
  16. * User -- user : 将Java的一个一个对象保存到数据库中(表里面的一行一行数据)
  17. * user -- Java : 将数据库表中一行一行的数据映射到我们的Java对象中
  18. * */
  19. public class BaseDao<T> {
  20. /**
  21. * 编写通用查询方法(单个)
  22. * @param connection:数据库连接
  23. * @param sql:sql语句
  24. * @param clazz:映射到Java对象的类型
  25. * @param args:参数列表
  26. * @return
  27. * @throws SQLException
  28. * @throws IllegalAccessException
  29. * @throws InstantiationException
  30. * @throws SecurityException
  31. * @throws NoSuchFieldException
  32. */
  33. public T getOne(Connection connection,String sql,Class<T> clazz,Object...args) throws SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException {
  34. T t=null;
  35. //获取PreparedStatement对象对sql语句预编译
  36. PreparedStatement ps = connection.prepareStatement(sql);
  37. if(args!=null && args.length>0) {
  38. for(int i = 0; i < args.length;i++) {
  39. ps.setObject(i+1, args[i]);//给占位符?赋值
  40. }
  41. }
  42. //执行
  43. ResultSet rs = ps.executeQuery();
  44. if(rs.next()) {
  45. //调用当前T类的无参构造方法
  46. t =clazz.newInstance();
  47. //如果有数据,那么读取每一列数据
  48. //通过rs的方法获取当前sql语句操作所在的表的元数据信息
  49. ResultSetMetaData rsmd = rs.getMetaData();
  50. //获取变得列总数
  51. int columnCount = rsmd.getColumnCount();
  52. System.out.println("columnCount:" + columnCount);
  53. for(int i= 0; i < columnCount ; i++) {
  54. //获取当前列的值
  55. Object columnValue = rs.getObject(i+1);
  56. //获取数据库的列名
  57. String columnLabel = rsmd.getColumnLabel(i+1);//user_id -- userId
  58. //通过列名匹配Java对象中的属性名
  59. Field field = clazz.getDeclaredField(columnLabel);// 当前Java对象中的属性对象
  60. //开启权限
  61. field.setAccessible(true);
  62. //给当前查找到的属性赋值
  63. field.set(t, columnValue);
  64. }
  65. }
  66. return t;
  67. }
  68. /**
  69. * 编写通用查询方法(列表)
  70. * @throws SQLException
  71. * @throws IllegalAccessException
  72. * @throws InstantiationException
  73. * @throws SecurityException
  74. * @throws NoSuchFieldException
  75. */
  76. public List<T> getList(Connection connection,String sql,Class<T> clazz,Object...args) throws SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException{
  77. List<T> list = new ArrayList<>();
  78. PreparedStatement ps = connection.prepareStatement(sql);
  79. if(args!=null && args.length>0) {
  80. //给占位符赋值
  81. for(int i=0;i<args.length;i++) {
  82. ps.setObject(i+1, args[i]);//给占位符?赋值
  83. }
  84. }
  85. //执行
  86. ResultSet rs = ps.executeQuery();
  87. //通过rs的方法获取当前sql语句操作所在的表的元数据信息
  88. ResultSetMetaData rsmd = rs.getMetaData();
  89. //获取变得列总数
  90. int columnCount = rsmd.getColumnCount();
  91. System.out.println("columnCount:" + columnCount);
  92. while(rs.next()) {
  93. T t = clazz.newInstance();
  94. for(int i= 0; i < columnCount ; i++) {
  95. //获取当前列的值
  96. Object columnValue = rs.getObject(i+1);
  97. //获取数据库的列名
  98. String columnLabel = rsmd.getColumnLabel(i+1);//user_id -- userId
  99. //通过列名匹配Java对象中的属性名
  100. Field field = clazz.getDeclaredField(columnLabel);// 当前Java对象中的属性对象
  101. //开启权限
  102. field.setAccessible(true);
  103. //给当前查找到的属性赋值
  104. field.set(t, columnValue);
  105. }
  106. list.add(t);
  107. }
  108. return list;
  109. }
  110. /**
  111. * 通用增删改方法编写
  112. * @param connection:数据库连接
  113. * @param sql:sql语句
  114. * @param args:参数列表
  115. * @throws SQLException
  116. */
  117. public void update(Connection connection,String sql,Object...args) throws SQLException {
  118. //预编译
  119. PreparedStatement ps = connection.prepareStatement(sql);//预编译
  120. if(args!=null && args.length>0) {
  121. for(int i=0;i<args.length;i++) {
  122. ps.setObject(i+1, args[i]);
  123. }
  124. }
  125. int row = ps.executeUpdate();
  126. System.out.println(row);
  127. }
  128. }

04.创建实体类User.java

  1. package com.detian;
  2. import java.util.Date;
  3. public class User {
  4. private Integer userId;// user_id
  5. private String userName;// user_naem
  6. private Double price;//price
  7. private Date createTime;//create_time
  8. public Integer getUserId() {
  9. return userId;
  10. }
  11. public void setUserId(Integer userId) {
  12. this.userId = userId;
  13. }
  14. public String getUserName() {
  15. return userName;
  16. }
  17. public void setUserName(String userName) {
  18. this.userName = userName;
  19. }
  20. public Double getPrice() {
  21. return price;
  22. }
  23. public void setPrice(Double price) {
  24. this.price = price;
  25. }
  26. public Date getCreateTime() {
  27. return createTime;
  28. }
  29. public void setCreateTime(Date createTime) {
  30. this.createTime = createTime;
  31. }
  32. public User() {
  33. // TODO Auto-generated constructor stub
  34. }
  35. public User(Integer userId, String userName, Double price, Date createTime) {
  36. super();
  37. this.userId = userId;
  38. this.userName = userName;
  39. this.price = price;
  40. this.createTime = createTime;
  41. }
  42. @Override
  43. public String toString() {
  44. return "User [userId=" + userId + ", userName=" + userName + ", price=" + price + ", createTime=" + createTime
  45. + "]";
  46. }
  47. }

05.CURD,新建文件TestBaseDao.java

  1. package com.detian;
  2. import java.sql.Connection;
  3. import java.sql.Date;
  4. import java.sql.SQLException;
  5. import java.util.List;
  6. import org.junit.Test;
  7. public class TestBaseDao {
  8. BaseDao<User> baseDao = new BaseDao<User>();
  9. @Test
  10. public void testGetOne() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException {
  11. Connection connection = JdbcUtil3.getConnection();
  12. String sql = "SELECT user_id as userId,user_name as userName,price,create_time as createTime FROM user WHERE user_id=?";
  13. User user = baseDao.getOne(connection, sql, User.class, 1013);
  14. System.out.println(user);
  15. }
  16. @Test
  17. public void testGetList() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException {
  18. Connection connection = JdbcUtil3.getConnection();
  19. //错误的写法
  20. //String sql = "SELECT user_id as userId,user_name as userName,price,create_time as createTime FROM user WHERE user_name LIKE '%'?'%'";
  21. //方法一
  22. //String sql = "SELECT user_id as userId,user_name as userName,price,create_time as createTime FROM user WHERE user_name LIKE \"%\"?\"%\"";
  23. //List<User> list = baseDao.getList(connection, sql, User.class,"李");
  24. //方法二
  25. String sql = "SELECT user_id as userId,user_name as userName,price,create_time as createTime FROM user WHERE user_name LIKE ?";
  26. List<User> list = baseDao.getList(connection, sql, User.class,"%李%");
  27. System.out.println(list);
  28. }
  29. @Test
  30. public void testAdd() throws ClassNotFoundException, SQLException {
  31. Connection connection = JdbcUtil3.getConnection();
  32. String sql="INSERT INTO user(user_name,price,create_time) VALUES(?,?,?)";
  33. baseDao.update(connection, sql, "张三",188,new Date( new java.util.Date().getTime()));
  34. JdbcUtil3.close();
  35. }
  36. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/575431
推荐阅读
相关标签
  

闽ICP备14008679号