jdbc操作mysql数据库

àì夳堔傛蜴生んèń 2022-08-10 09:54 302阅读 0赞

如何操作mysql数据库进行crud:

第一步:创建数据库

  1. DROP TABLE IF EXISTS `jdbc_user`;
  2. CREATE TABLE `jdbc_user` (
  3. `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  4. `name` varchar(255) DEFAULT NULL COMMENT '户用名',
  5. `password` varchar(255) DEFAULT NULL COMMENT '户用密码',
  6. PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

第二步:导入mysql-connector-java的jar包

第三步:创建实体类:

  1. package com.jdbc.entity;
  2. /**
  3. * 用户实体类 如果觉得 get / set 方法比较冗余,可以考虑使用lombok
  4. *
  5. * @author ITDragon
  6. *
  7. */
  8. public class User implements java.io.Serializable {
  9. /**
  10. * 第一步:实体类序列化
  11. * 第二步:定义属性
  12. * 第三步:生成get/set方法
  13. * 第四步:创建带主键参数的构造方法
  14. * 第五步:生成toString()方便看结果
  15. */
  16. private Integer id; // 用户id
  17. private String name; // 用户名
  18. private String password; // 用户密码
  19. public User() {
  20. }
  21. public User(Integer id) {
  22. this.id = id;
  23. }
  24. public Integer getId() {
  25. return id;
  26. }
  27. public void setId(Integer id) {
  28. this.id = id;
  29. }
  30. public String getName() {
  31. return name;
  32. }
  33. public void setName(String name) {
  34. this.name = name;
  35. }
  36. public String getPassword() {
  37. return password;
  38. }
  39. public void setPassword(String password) {
  40. this.password = password;
  41. }
  42. @Override
  43. public String toString() {
  44. return "User [id=" + id + ", name=" + name + ", password=" + password
  45. + "]";
  46. }
  47. }

第四步:创建链接数据库工具类

  1. package com.jdbc.util;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.Statement;
  7. /**
  8. * 数据库连接类
  9. * @author ITDragon
  10. *
  11. */
  12. public class ConnectionUtil {
  13. /**
  14. * 第一步:加载驱动
  15. * 第二步:链接数据库
  16. * 第三步:一定要关闭流
  17. * 第四步:测试是否连接成功
  18. */
  19. private static String DRIVER = "com.mysql.jdbc.Driver"; // 数据库驱动
  20. private static String URL = "jdbc:mysql://localhost:3306/test"; // 访问数据库路径
  21. private static String NAME = "root"; // 数据库用户名
  22. private static String PASSWORD = "root"; // 数据库密码
  23. public static Connection getConnection() {
  24. Connection connection = null;
  25. try {
  26. // 加载驱动
  27. Class.forName(DRIVER);
  28. // 连接数据库
  29. connection = DriverManager.getConnection(URL, NAME, PASSWORD);
  30. return connection;
  31. } catch (Exception e) {
  32. return null;
  33. }
  34. }
  35. // 关闭流
  36. public static void closeConnection(Connection connection) {
  37. try {
  38. connection.close();
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. public static void closeStatement(Statement statement) {
  44. try {
  45. statement.close();
  46. } catch (Exception e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. public static void closePreparedStatement(PreparedStatement pStatement) {
  51. try {
  52. pStatement.close();
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. public static void closeResultSet(ResultSet rs) {
  58. try {
  59. rs.close();
  60. } catch (Exception e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. // 测试数据库是否链接成功
  65. public static void main(String[] args) {
  66. System.out.println(getConnection());
  67. }
  68. }

执行出现类似于com.mysql.jdbc.JDBC4Connection@1b8cdd5则表示执行成功

第五步:核心代码

  1. package com.jdbc.dao;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import com.jdbc.entity.User;
  8. import com.jdbc.util.ConnectionUtil;
  9. public class UserDao {
  10. /**
  11. *
  12. * 插入数据(根据JavaBean的内容插入;所以要导入Dao类) 方法名:saveDao<BR>
  13. * 创建人:ITDragon <BR>
  14. * 时间:2015年2月6日-下午8:33:09 <BR>
  15. *
  16. * @param dao
  17. * @return boolean<BR>
  18. * @exception <BR>
  19. * @since 1.0.0
  20. */
  21. public static boolean saveDao(User user) {
  22. String sql = "insert into jdbc_user(name,password) values(?,?)";
  23. Connection connection = null;
  24. PreparedStatement pStatement = null;
  25. try {
  26. connection = ConnectionUtil.getConnection();
  27. pStatement = connection.prepareStatement(sql);
  28. pStatement.setString(1, user.getName());
  29. pStatement.setString(2, user.getPassword());
  30. int count = pStatement.executeUpdate();
  31. return count > 0 ? true : false;
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. return false;
  35. } finally {
  36. ConnectionUtil.closePreparedStatement(pStatement);
  37. ConnectionUtil.closeConnection(connection);
  38. }
  39. }
  40. /**
  41. *
  42. * 查询数据 方法名:findDaos<BR>
  43. * 创建人:ITDragon <BR>
  44. * 时间:2015年2月6日-下午8:55:05 <BR>
  45. *
  46. * @return List<Dao><BR>
  47. * @exception <BR>
  48. * @since 1.0.0
  49. */
  50. public static List<User> findUsers() {
  51. String sql = "select * from jdbc_user";
  52. Connection connection = null;
  53. PreparedStatement pStatement = null;
  54. ResultSet rs = null;
  55. List<User> users = null;
  56. try {
  57. connection = ConnectionUtil.getConnection();
  58. pStatement = connection.prepareStatement(sql);
  59. rs = pStatement.executeQuery();
  60. users = new ArrayList<User>();
  61. while (rs.next()) {
  62. User user = new User();
  63. user.setId(rs.getInt("id"));
  64. user.setName(rs.getString("name"));
  65. user.setPassword(rs.getString("password"));
  66. users.add(user);
  67. }
  68. return users;
  69. } catch (Exception e) {
  70. e.printStackTrace();
  71. return null;
  72. } finally {
  73. ConnectionUtil.closeResultSet(rs);
  74. ConnectionUtil.closePreparedStatement(pStatement);
  75. ConnectionUtil.closeConnection(connection);
  76. }
  77. }
  78. /**
  79. *
  80. * 根据主键id删除 方法名:deleteUser<BR>
  81. * 创建人:ITDragon <BR>
  82. * 时间:2015年2月6日-下午9:03:55 <BR>
  83. *
  84. * @param id
  85. * @return boolean<BR>
  86. * @exception <BR>
  87. * @since 1.0.0
  88. */
  89. public static boolean deleteUser(Integer id) {
  90. String sql = "delete from jdbc_user where id = ?";
  91. Connection connection = null;
  92. PreparedStatement pStatement = null;
  93. try {
  94. connection = ConnectionUtil.getConnection();
  95. pStatement = connection.prepareStatement(sql);
  96. pStatement.setInt(1, id);
  97. int count = pStatement.executeUpdate();
  98. return count > 0 ? true : false;
  99. } catch (Exception e) {
  100. e.printStackTrace();
  101. return false;
  102. } finally {
  103. ConnectionUtil.closePreparedStatement(pStatement);
  104. ConnectionUtil.closeConnection(connection);
  105. }
  106. }
  107. /**
  108. *
  109. * 根据主键id修改数据 方法名:updateUser<BR>
  110. * 创建人:ITDragon <BR>
  111. * 时间:2015年2月6日-下午9:17:03 <BR>
  112. *
  113. * @param name
  114. * @param password
  115. * @param id
  116. * @return boolean<BR>
  117. * @exception <BR>
  118. * @since 1.0.0
  119. */
  120. public static boolean updateUser(String name, String password, Integer id) {
  121. // name 和 password之间只能用 ","隔开
  122. String sql = "update jdbc_user set name = ? , password = ? where id = ?";
  123. Connection connection = null;
  124. PreparedStatement pStatement = null;
  125. try {
  126. connection = ConnectionUtil.getConnection();
  127. pStatement = connection.prepareStatement(sql);
  128. pStatement.setString(1, name);
  129. pStatement.setString(2, password);
  130. pStatement.setInt(3, id);
  131. int count = pStatement.executeUpdate();
  132. return count > 0 ? true : false;
  133. } catch (Exception e) {
  134. e.printStackTrace();
  135. return false;
  136. } finally {
  137. ConnectionUtil.closePreparedStatement(pStatement);
  138. ConnectionUtil.closeConnection(connection);
  139. }
  140. }
  141. }

第六步:测试类

  1. package com.jdbc.test;
  2. import java.util.List;
  3. import org.junit.Test;
  4. import com.jdbc.dao.UserDao;
  5. import com.jdbc.entity.User;
  6. /**
  7. * 测试User的crud
  8. * @author ITDragon
  9. *
  10. */
  11. public class UserTest {
  12. @Test
  13. public void findUserTest(){
  14. List<User> users= UserDao.findUsers();
  15. for (User user : users) {
  16. System.out.println(user);
  17. }
  18. }
  19. @Test
  20. public void saveUserTest(){
  21. User user = new User();
  22. user.setName("ITDragon");
  23. user.setPassword("麻麻说密码太长容易记得");
  24. boolean flag = UserDao.saveDao(user);
  25. if (flag) {
  26. System.out.println(user.getName()+"保存成功");
  27. } else {
  28. System.out.println("保存失败");
  29. }
  30. }
  31. @Test
  32. public void updateUserTest(){
  33. boolean flag = UserDao.updateUser("NewITDragon", "麻麻说错了", 1);
  34. if (flag) {
  35. System.out.println("更新成功");
  36. } else {
  37. System.out.println("更新失败");
  38. }
  39. }
  40. @Test
  41. public void deleteUserTest(){
  42. boolean flag = UserDao.deleteUser(1);
  43. if (flag) {
  44. System.out.println("删除成功");
  45. } else {
  46. System.out.println("删除失败");
  47. }
  48. }
  49. }

资料下载地址:http://download.csdn.net/detail/qq_19558705/9285827

个人主页:http://www.itit123.cn/ 更多干货等你来拿

有什么疑问和建议可以留言。

发表评论

表情:
评论列表 (有 0 条评论,302人围观)

还没有评论,来说两句吧...

相关阅读