JDBC连接MySQL

虽然在项目中通常用ORM的框架实现持久化。但经常因测试某些技术的需要,要写一个完整的JDBC查询数据库。写一个在这儿备份。

首先引入驱动包:

  1. <dependencies>
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. <version>5.1.38</version>
  6. </dependency>
  7. </dependencies>

写一个简单的连接测试是否能查询数据:

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.Statement;
  5.  
  6. public class JDBCTester {
  7.  
  8. public static void main(String[] args) throws Exception {
  9. Class.forName("com.mysql.jdbc.Driver");
  10. System.out.println("成功加载驱动");
  11.  
  12. Connection connection = null;
  13. Statement statement = null;
  14. ResultSet resultSet = null;
  15.  
  16. try {
  17. String url = "jdbc:mysql://localhost:3306/demo?user=root&password=123456&useUnicode=true&characterEncoding=UTF8";
  18. connection = DriverManager.getConnection(url);
  19. System.out.println("成功获取连接");
  20.  
  21. statement = connection.createStatement();
  22. String sql = "select * from t_balance";
  23. resultSet = statement.executeQuery(sql);
  24.  
  25. resultSet.beforeFirst();
  26. while (resultSet.next()) {
  27. System.out.println(resultSet.getString(1));
  28. }
  29. System.out.println("成功操作数据库");
  30. } catch(Throwable t) {
  31. // TODO 处理异常
  32. t.printStackTrace();
  33. } finally {
  34. if (resultSet != null) {
  35. resultSet.close();
  36. }
  37. if (statement != null) {
  38. statement.close();
  39. }
  40. if (connection != null) {
  41. connection.close();
  42. }
  43. System.out.println("成功关闭资源");
  44. }
  45.  
  46. }
  47.  
  48. }

看到以下日志,说明程序是正确的:

  1. 成功加载驱动
  2. 成功获取连接
  3. 1
  4. 成功操作数据库
  5. 成功关闭资源

JDBC的Connection默认是自动提交

case AutoCommit 描述 结果
1 Default(true) 没有异常,没有显式commit 更新
2 Default(true) 有异常,没有显式commit 更新
3 Default(true) 有异常,没有显式commit,有显式rollback 更新,异常包含Can't call rollback when autocommit=true

case 1:

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.ResultSetMetaData;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11.  
  12. public class JDBCTools {
  13.  
  14. public static void main(String[] args) throws Exception {
  15. JDBCTools.query("select * from t_balance t");
  16. System.out.println();
  17. JDBCTools.execute("update t_balance t set t.balance = 20000 where t.user_id = 100");
  18. System.out.println();
  19. JDBCTools.query("select * from t_balance t");
  20. }
  21.  
  22. public static String HOST = "localhost";
  23. public static String PORT = "3306";
  24. public static String DATABASE_NAME = "demo";
  25. public static String USER_NAME = "root";
  26. public static String PASSWORD = "123456";
  27.  
  28. /**
  29. * 获取数据库连接
  30. * @return 数据库连接
  31. */
  32. public static Connection getConn() throws Exception {
  33. Class.forName("com.mysql.jdbc.Driver");
  34. System.out.println("成功加载驱动");
  35.  
  36. String url = "jdbc:mysql://" + HOST + ":" + PORT + "/" + DATABASE_NAME + "?user=" + USER_NAME + "&password=" + PASSWORD + "&useUnicode=true&characterEncoding=UTF8";
  37. Connection connection = DriverManager.getConnection(url);
  38. System.out.println("成功获取连接");
  39. return connection;
  40. }
  41.  
  42. /**
  43. * 关闭资源
  44. */
  45. public static void closeResource(Connection conn, Statement st, ResultSet rs) {
  46. if (rs != null) {
  47. try {
  48. rs.close();
  49. } catch (SQLException e) {
  50. // TODO 处理异常
  51. e.printStackTrace();
  52. }
  53. }
  54. if (st != null) {
  55. try {
  56. st.close();
  57. } catch (SQLException e) {
  58. // TODO 处理异常
  59. e.printStackTrace();
  60. }
  61. }
  62. if (conn != null) {
  63. try {
  64. conn.close();
  65. } catch (SQLException e) {
  66. // TODO 处理异常
  67. e.printStackTrace();
  68. }
  69. }
  70. System.out.println("成功关闭资源");
  71. }
  72.  
  73. /**
  74. * 查询SQL
  75. * @param sql 查询语句
  76. * @return 数据集合
  77. * @throws SQLException
  78. */
  79. public static List<Map<String, String>> query(String sql) throws Exception {
  80. Connection connection = null;
  81. Statement statement = null;
  82. ResultSet resultSet = null;
  83. List<Map<String, String>> resultList = null;
  84.  
  85. try {
  86. connection = JDBCTools.getConn();
  87.  
  88. statement = connection.createStatement();
  89. resultSet = statement.executeQuery(sql);
  90. System.out.println("SQL : " + sql);
  91.  
  92. ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
  93. int columnCount = resultSetMetaData.getColumnCount();
  94. String[] columnNames = new String[columnCount + 1];
  95. for (int i = 1; i <= columnCount; i++) {
  96. columnNames[i] = resultSetMetaData.getColumnName(i);
  97. }
  98.  
  99. resultList = new ArrayList<Map<String, String>>();
  100. Map<String, String> resultMap = new HashMap<String, String>();
  101. resultSet.beforeFirst();
  102. while (resultSet.next()) {
  103. for (int i = 1; i <= columnCount; i++) {
  104. resultMap.put(columnNames[i], resultSet.getString(i));
  105. }
  106. resultList.add(resultMap);
  107. }
  108. System.out.println("成功查询数据库,查得数据:" + resultList);
  109. } catch(Throwable t) {
  110. // TODO 处理异常
  111. t.printStackTrace();
  112. } finally {
  113. JDBCTools.closeResource(connection, statement, resultSet);
  114. }
  115.  
  116. return resultList;
  117. }
  118.  
  119. /**
  120. * 执行SQL
  121. * @param sql 执行的SQL
  122. * @return 操作条数
  123. */
  124. public static int execute(String sql) throws Exception {
  125. Connection connection = null;
  126. Statement statement = null;
  127. ResultSet resultSet = null;
  128. int num = 0;
  129.  
  130. try {
  131. connection = JDBCTools.getConn();
  132.  
  133. statement = connection.createStatement();
  134. num = statement.executeUpdate(sql);
  135. System.out.println("SQL : " + sql);
  136. System.out.println("成功操作数据库,影响条数:" + num);
  137.  
  138. // 模拟异常,用于测试事务
  139. /*
  140. if (1 == 1) {
  141. throw new RuntimeException();
  142. }
  143. */
  144.  
  145. } catch(Exception e) {
  146. // 处理异常:回滚事务后抛出异常
  147. e.printStackTrace();
  148. // connection.rollback();
  149. System.out.println("事务回滚");
  150. throw e;
  151. } finally {
  152. JDBCTools.closeResource(connection, statement, resultSet);
  153. }
  154.  
  155. return num;
  156. }
  157.  
  158. }
  1. 成功加载驱动
  2. 成功获取连接
  3. SQL : select * from t_balance t
  4. 成功查询数据库,查得数据:[{id=1, balance=10000, user_id=100}]
  5. 成功关闭资源
  6.  
  7. 成功加载驱动
  8. 成功获取连接
  9. SQL : update t_balance t set t.balance = 20000 where t.user_id = 100
  10. 成功操作数据库,影响条数:1
  11. 成功关闭资源
  12.  
  13. 成功加载驱动
  14. 成功获取连接
  15. SQL : select * from t_balance t
  16. 成功查询数据库,查得数据:[{id=1, balance=20000, user_id=100}]
  17. 成功关闭资源

case 2 :

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.ResultSetMetaData;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11.  
  12. public class JDBCTools {
  13.  
  14. public static void main(String[] args) throws Exception {
  15. JDBCTools.query("select * from t_balance t");
  16. System.out.println();
  17. JDBCTools.execute("update t_balance t set t.balance = 20000 where t.user_id = 100");
  18. System.out.println();
  19. JDBCTools.query("select * from t_balance t");
  20. }
  21.  
  22. public static String HOST = "localhost";
  23. public static String PORT = "3306";
  24. public static String DATABASE_NAME = "demo";
  25. public static String USER_NAME = "root";
  26. public static String PASSWORD = "123456";
  27.  
  28. /**
  29. * 获取数据库连接
  30. * @return 数据库连接
  31. */
  32. public static Connection getConn() throws Exception {
  33. Class.forName("com.mysql.jdbc.Driver");
  34. System.out.println("成功加载驱动");
  35.  
  36. String url = "jdbc:mysql://" + HOST + ":" + PORT + "/" + DATABASE_NAME + "?user=" + USER_NAME + "&password=" + PASSWORD + "&useUnicode=true&characterEncoding=UTF8";
  37. Connection connection = DriverManager.getConnection(url);
  38. System.out.println("成功获取连接");
  39. return connection;
  40. }
  41.  
  42. /**
  43. * 关闭资源
  44. */
  45. public static void closeResource(Connection conn, Statement st, ResultSet rs) {
  46. if (rs != null) {
  47. try {
  48. rs.close();
  49. } catch (SQLException e) {
  50. // TODO 处理异常
  51. e.printStackTrace();
  52. }
  53. }
  54. if (st != null) {
  55. try {
  56. st.close();
  57. } catch (SQLException e) {
  58. // TODO 处理异常
  59. e.printStackTrace();
  60. }
  61. }
  62. if (conn != null) {
  63. try {
  64. conn.close();
  65. } catch (SQLException e) {
  66. // TODO 处理异常
  67. e.printStackTrace();
  68. }
  69. }
  70. System.out.println("成功关闭资源");
  71. }
  72.  
  73. /**
  74. * 查询SQL
  75. * @param sql 查询语句
  76. * @return 数据集合
  77. * @throws SQLException
  78. */
  79. public static List<Map<String, String>> query(String sql) throws Exception {
  80. Connection connection = null;
  81. Statement statement = null;
  82. ResultSet resultSet = null;
  83. List<Map<String, String>> resultList = null;
  84.  
  85. try {
  86. connection = JDBCTools.getConn();
  87.  
  88. statement = connection.createStatement();
  89. resultSet = statement.executeQuery(sql);
  90. System.out.println("SQL : " + sql);
  91.  
  92. ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
  93. int columnCount = resultSetMetaData.getColumnCount();
  94. String[] columnNames = new String[columnCount + 1];
  95. for (int i = 1; i <= columnCount; i++) {
  96. columnNames[i] = resultSetMetaData.getColumnName(i);
  97. }
  98.  
  99. resultList = new ArrayList<Map<String, String>>();
  100. Map<String, String> resultMap = new HashMap<String, String>();
  101. resultSet.beforeFirst();
  102. while (resultSet.next()) {
  103. for (int i = 1; i <= columnCount; i++) {
  104. resultMap.put(columnNames[i], resultSet.getString(i));
  105. }
  106. resultList.add(resultMap);
  107. }
  108. System.out.println("成功查询数据库,查得数据:" + resultList);
  109. } catch(Throwable t) {
  110. // TODO 处理异常
  111. t.printStackTrace();
  112. } finally {
  113. JDBCTools.closeResource(connection, statement, resultSet);
  114. }
  115.  
  116. return resultList;
  117. }
  118.  
  119. /**
  120. * 执行SQL
  121. * @param sql 执行的SQL
  122. * @return 操作条数
  123. */
  124. public static int execute(String sql) throws Exception {
  125. Connection connection = null;
  126. Statement statement = null;
  127. ResultSet resultSet = null;
  128. int num = 0;
  129.  
  130. try {
  131. connection = JDBCTools.getConn();
  132.  
  133. statement = connection.createStatement();
  134. num = statement.executeUpdate(sql);
  135. System.out.println("SQL : " + sql);
  136. System.out.println("成功操作数据库,影响条数:" + num);
  137.  
  138. // 模拟异常,用于测试事务
  139. if (1 == 1) {
  140. throw new RuntimeException();
  141. }
  142.  
  143. } catch(Exception e) {
  144. // 处理异常:回滚事务后抛出异常
  145. e.printStackTrace();
  146. // connection.rollback();
  147. System.out.println("事务回滚");
  148. throw e;
  149. } finally {
  150. JDBCTools.closeResource(connection, statement, resultSet);
  151. }
  152.  
  153. return num;
  154. }
  155.  
  156. }
  1. 成功加载驱动
  2. 成功获取连接
  3. SQL : select * from t_balance t
  4. 成功查询数据库,查得数据:[{id=1, balance=10000, user_id=100}]
  5. 成功关闭资源
  6.  
  7. 成功加载驱动
  8. 成功获取连接
  9. SQL : update t_balance t set t.balance = 20000 where t.user_id = 100
  10. 成功操作数据库,影响条数:1
  11. 事务回滚
  12. java.lang.RuntimeException
  13. at JDBCTools.execute(JDBCTools.java:140)
  14. at JDBCTools.main(JDBCTools.java:17)
  15. 成功关闭资源
  16. Exception in thread "main" java.lang.RuntimeException
  17. at JDBCTools.execute(JDBCTools.java:140)
  18. at JDBCTools.main(JDBCTools.java:17)

case 3 :

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.ResultSetMetaData;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11.  
  12. public class JDBCTools {
  13.  
  14. public static void main(String[] args) throws Exception {
  15. JDBCTools.query("select * from t_balance t");
  16. System.out.println();
  17. JDBCTools.execute("update t_balance t set t.balance = 20000 where t.user_id = 100");
  18. System.out.println();
  19. JDBCTools.query("select * from t_balance t");
  20. }
  21.  
  22. public static String HOST = "localhost";
  23. public static String PORT = "3306";
  24. public static String DATABASE_NAME = "demo";
  25. public static String USER_NAME = "root";
  26. public static String PASSWORD = "123456";
  27.  
  28. /**
  29. * 获取数据库连接
  30. * @return 数据库连接
  31. */
  32. public static Connection getConn() throws Exception {
  33. Class.forName("com.mysql.jdbc.Driver");
  34. System.out.println("成功加载驱动");
  35.  
  36. String url = "jdbc:mysql://" + HOST + ":" + PORT + "/" + DATABASE_NAME + "?user=" + USER_NAME + "&password=" + PASSWORD + "&useUnicode=true&characterEncoding=UTF8";
  37. Connection connection = DriverManager.getConnection(url);
  38. System.out.println("成功获取连接");
  39. return connection;
  40. }
  41.  
  42. /**
  43. * 关闭资源
  44. */
  45. public static void closeResource(Connection conn, Statement st, ResultSet rs) {
  46. if (rs != null) {
  47. try {
  48. rs.close();
  49. } catch (SQLException e) {
  50. // TODO 处理异常
  51. e.printStackTrace();
  52. }
  53. }
  54. if (st != null) {
  55. try {
  56. st.close();
  57. } catch (SQLException e) {
  58. // TODO 处理异常
  59. e.printStackTrace();
  60. }
  61. }
  62. if (conn != null) {
  63. try {
  64. conn.close();
  65. } catch (SQLException e) {
  66. // TODO 处理异常
  67. e.printStackTrace();
  68. }
  69. }
  70. System.out.println("成功关闭资源");
  71. }
  72.  
  73. /**
  74. * 查询SQL
  75. * @param sql 查询语句
  76. * @return 数据集合
  77. * @throws SQLException
  78. */
  79. public static List<Map<String, String>> query(String sql) throws Exception {
  80. Connection connection = null;
  81. Statement statement = null;
  82. ResultSet resultSet = null;
  83. List<Map<String, String>> resultList = null;
  84.  
  85. try {
  86. connection = JDBCTools.getConn();
  87.  
  88. statement = connection.createStatement();
  89. resultSet = statement.executeQuery(sql);
  90. System.out.println("SQL : " + sql);
  91.  
  92. ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
  93. int columnCount = resultSetMetaData.getColumnCount();
  94. String[] columnNames = new String[columnCount + 1];
  95. for (int i = 1; i <= columnCount; i++) {
  96. columnNames[i] = resultSetMetaData.getColumnName(i);
  97. }
  98.  
  99. resultList = new ArrayList<Map<String, String>>();
  100. Map<String, String> resultMap = new HashMap<String, String>();
  101. resultSet.beforeFirst();
  102. while (resultSet.next()) {
  103. for (int i = 1; i <= columnCount; i++) {
  104. resultMap.put(columnNames[i], resultSet.getString(i));
  105. }
  106. resultList.add(resultMap);
  107. }
  108. System.out.println("成功查询数据库,查得数据:" + resultList);
  109. } catch(Throwable t) {
  110. // TODO 处理异常
  111. t.printStackTrace();
  112. } finally {
  113. JDBCTools.closeResource(connection, statement, resultSet);
  114. }
  115.  
  116. return resultList;
  117. }
  118.  
  119. /**
  120. * 执行SQL
  121. * @param sql 执行的SQL
  122. * @return 操作条数
  123. */
  124. public static int execute(String sql) throws Exception {
  125. Connection connection = null;
  126. Statement statement = null;
  127. ResultSet resultSet = null;
  128. int num = 0;
  129.  
  130. try {
  131. connection = JDBCTools.getConn();
  132.  
  133. statement = connection.createStatement();
  134. num = statement.executeUpdate(sql);
  135. System.out.println("SQL : " + sql);
  136. System.out.println("成功操作数据库,影响条数:" + num);
  137.  
  138. // 模拟异常,用于测试事务
  139. if (1 == 1) {
  140. throw new RuntimeException();
  141. }
  142.  
  143. } catch(Exception e) {
  144. // 处理异常:回滚事务后抛出异常
  145. e.printStackTrace();
  146. connection.rollback();
  147. System.out.println("事务回滚");
  148. throw e;
  149. } finally {
  150. JDBCTools.closeResource(connection, statement, resultSet);
  151. }
  152.  
  153. return num;
  154. }
  155.  
  156. }
  1. 成功加载驱动
  2. 成功获取连接
  3. SQL : select * from t_balance t
  4. 成功查询数据库,查得数据:[{id=1, balance=10000, user_id=100}]
  5. 成功关闭资源
  6.  
  7. 成功加载驱动
  8. 成功获取连接
  9. SQL : update t_balance t set t.balance = 20000 where t.user_id = 100
  10. 成功操作数据库,影响条数:1
  11. java.lang.RuntimeException
  12. at JDBCTools.execute(JDBCTools.java:140)
  13. at JDBCTools.main(JDBCTools.java:17)
  14. 成功关闭资源
  15. Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Can't call rollback when autocommit=true
  16. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  17. at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
  18. at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
  19. at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
  20. at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
  21. at com.mysql.jdbc.Util.getInstance(Util.java:387)
  22. at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:917)
  23. at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
  24. at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
  25. at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
  26. at com.mysql.jdbc.ConnectionImpl.rollback(ConnectionImpl.java:4618)
  27. at JDBCTools.execute(JDBCTools.java:146)
  28. at JDBCTools.main(JDBCTools.java:17)

最简单的工具类

封装个简单的查询MySQL的工具类更方便使用。注:此实现非常简单,仅用于日常测试,不适合生产环境使用。

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.ResultSetMetaData;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11.  
  12. public class JDBCTools {
  13.  
  14. public static void main(String[] args) throws Exception {
  15. JDBCTools.query("select * from t_balance t");
  16. JDBCTools.execute("update t_balance t set t.balance = 20000 where t.user_id = 100");
  17. JDBCTools.query("select * from t_balance t");
  18. }
  19.  
  20. public static String HOST = "localhost";
  21. public static String PORT = "3306";
  22. public static String DATABASE_NAME = "demo";
  23. public static String USER_NAME = "root";
  24. public static String PASSWORD = "123456";
  25.  
  26. /**
  27. * 获取数据库连接
  28. * @return 数据库连接
  29. */
  30. public static Connection getConn() throws Exception {
  31. Class.forName("com.mysql.jdbc.Driver");
  32. System.out.println("成功加载驱动");
  33.  
  34. String url = "jdbc:mysql://" + HOST + ":" + PORT + "/" + DATABASE_NAME + "?user=" + USER_NAME + "&password=" + PASSWORD + "&useUnicode=true&characterEncoding=UTF8";
  35. Connection connection = DriverManager.getConnection(url);
  36. System.out.println("成功获取连接");
  37. return connection;
  38. }
  39.  
  40. /**
  41. * 关闭资源
  42. */
  43. public static void closeResource(Connection conn, Statement st, ResultSet rs) {
  44. if (rs != null) {
  45. try {
  46. rs.close();
  47. } catch (SQLException e) {
  48. // TODO 处理异常
  49. e.printStackTrace();
  50. }
  51. }
  52. if (st != null) {
  53. try {
  54. st.close();
  55. } catch (SQLException e) {
  56. // TODO 处理异常
  57. e.printStackTrace();
  58. }
  59. }
  60. if (conn != null) {
  61. try {
  62. conn.close();
  63. } catch (SQLException e) {
  64. // TODO 处理异常
  65. e.printStackTrace();
  66. }
  67. }
  68. System.out.println("成功关闭资源");
  69. }
  70.  
  71. /**
  72. * 查询SQL
  73. * @param sql 查询语句
  74. * @return 数据集合
  75. * @throws SQLException
  76. */
  77. public static List<Map<String, String>> query(String sql) throws Exception {
  78. Connection connection = null;
  79. Statement statement = null;
  80. ResultSet resultSet = null;
  81. List<Map<String, String>> resultList = null;
  82.  
  83. try {
  84. connection = JDBCTools.getConn();
  85.  
  86. statement = connection.createStatement();
  87. resultSet = statement.executeQuery(sql);
  88.  
  89. ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
  90. int columnCount = resultSetMetaData.getColumnCount();
  91. String[] columnNames = new String[columnCount + 1];
  92. for (int i = 1; i <= columnCount; i++) {
  93. columnNames[i] = resultSetMetaData.getColumnName(i);
  94. }
  95.  
  96. resultList = new ArrayList<Map<String, String>>();
  97. Map<String, String> resultMap = new HashMap<String, String>();
  98. resultSet.beforeFirst();
  99. while (resultSet.next()) {
  100. for (int i = 1; i <= columnCount; i++) {
  101. resultMap.put(columnNames[i], resultSet.getString(i));
  102. }
  103. resultList.add(resultMap);
  104. }
  105. System.out.println("成功查询数据库,查得数据:" + resultList);
  106. } catch(Throwable t) {
  107. // TODO 处理异常
  108. t.printStackTrace();
  109. } finally {
  110. JDBCTools.closeResource(connection, statement, resultSet);
  111. }
  112.  
  113. return resultList;
  114. }
  115.  
  116. /**
  117. * 执行SQL
  118. * @param sql 执行的SQL
  119. * @return 操作条数
  120. */
  121. public static int execute(String sql) throws Exception {
  122. Connection connection = null;
  123. Statement statement = null;
  124. ResultSet resultSet = null;
  125. int num = 0;
  126.  
  127. try {
  128. connection = JDBCTools.getConn();
  129. connection.setAutoCommit(false);
  130.  
  131. statement = connection.createStatement();
  132. num = statement.executeUpdate(sql);
  133. System.out.println("成功操作数据库,影响条数:" + num);
  134.  
  135. // 模拟异常,用于测试事务
  136. /*
  137. if (1 == 1) {
  138. throw new RuntimeException();
  139. }
  140. */
  141.  
  142. connection.commit();
  143. } catch(Exception e) {
  144. // 处理异常:回滚事务后抛出异常
  145. e.printStackTrace();
  146. connection.rollback();
  147. System.out.println("事务回滚");
  148. throw e;
  149. } finally {
  150. JDBCTools.closeResource(connection, statement, resultSet);
  151. }
  152.  
  153. return num;
  154. }
  155.  
  156. }

【Java】JDBC连接MySQL的更多相关文章

  1. java jdbc 连接mysql数据库 实现增删改查

    好久没有写博文了,写个简单的东西热热身,分享给大家. jdbc相信大家都不陌生,只要是个搞java的,最初接触j2ee的时候都是要学习这么个东西的,谁叫程序得和数据库打交道呢!而jdbc就是和数据库打 ...

  2. java jdbc 连接mysql 数据库

    JDBC连接MySQL 加载及注册JDBC驱动程序 Class.forName("com.mysql.jdbc.Driver"); Class.forName("com. ...

  3. java jdbc连接mysql

    JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口 ...

  4. JAVA使用jdbc连接MYSQL简单示例

    以下展示的为JAVA使用jdbc连接MYSQL简单示例: import java.sql.DriverManager; import java.sql.ResultSet; import java.s ...

  5. java用JDBC连接MySQL数据库的详细知识点

    想实现java用JDBC连接MySQL数据库.需要有几个准备工作: 1.下载Connector/J的库文件,下载Connector/J的官网地址:http://www.mysql.com/downlo ...

  6. Java编程学习之JDBC连接MySQL

    JDBC连接MySQL 一.对JDBC连接数据库的步骤1.加载数据库驱动//加载驱动Class.forName(driverClass)-------------------------------- ...

  7. (Win10)Java,Maven,Tomcat8.0,Mysql8.0.15安装与环境配置,以及IDEA2019.3使用JDBC连接MySQL、创建JavaEE项目

    之前用windows+linux的双系统,最近不怎么舒服就把双系统给卸了,没想到除了问题,导致有linux残余,于是就一狠心重装了电脑,又把Java及其相关的一些东西重新装了回来,还好当初存了网盘链接 ...

  8. ava基础MySQL存储过程 Java基础 JDBC连接MySQL数据库

    1.MySQL存储过程   1.1.什么是存储过程 带有逻辑的sql语句:带有流程控制语句(if  while)等等 的sql语句   1.2.存储过程的特点 1)执行效率非常快,存储过程是数据库的服 ...

  9. JDBC连接MySQL数据库代码模板

    下面这个例子是最简单的JDBC连接MySQL数据库的例子. 一般步骤: 1.注册驱动: 2.建立连接: 3.创建语句: 4.处理结果: 5.释放资源. 注意: 1.软件开发环境:MyEclipse 8 ...

随机推荐

  1. 。。。JDBC里面的sql与hibernate里面的hql有关占位符"?"的总结。。。

    今天在看Hibernate的时候,似乎又有了一些收获的东东,嘻嘻... 我记得很清楚:以前用JDBC操作数据库的时候是这样的: String sql = "select * from use ...

  2. CCF真题之出现次数最多的数

    201312-1 问题描述 给定n个正整数,找出它们中出现次数最多的数.如果这样的数有多个,请输出其中最小的一个. 输入格式 输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数. ...

  3. AS-demo09

    ,mainifast: <uses-permission android:name="android.permission.SET_WALLPAPER"/> , < ...

  4. SSH+DWZ、JQuery-UI ,swfobject.embedSWF属性与用法,IE下日期控件被flash控件挡住

    ---恢复内容开始--- 最近在做SSH+DWZ(JQuery-UI)项目,在用到图表问题的时候,出现在IE下面,日期控件被flash被挡住而不能选取日期情况,经在网络搜查,现在解决办法如下: 1.首 ...

  5. java web sql注入测试(1)---概念概述

    在进行java web 测试时,经常会忽略的测试种类就是sql注入测试,这类缺陷造成的原因是开发技术在这方面欠缺的表现,虽然不常见,但一旦有这类缺陷,就很因此对运营的数据造成很多不必要的损失,所以,还 ...

  6. Android 多线程通信 访问网络

    package org.rongguang.testthread; import android.app.Activity; import android.os.Bundle; import andr ...

  7. RMB转换人民币大小金额

    MXS&Vincene  ─╄OvЁ  &0000015 ─╄OvЁ  MXS&Vincene MXS&Vincene  ─╄OvЁ:今天很残酷,明天更残酷,后天很美好 ...

  8. 某硕笔试题mysql数据库部分(较为全面)

    Student(S#,Sname,Sage,Ssex) 学生表  Course(C#,Cname,T#) 课程表  SC(S#,C#,score) 成绩表  Teacher(T#,Tname) 教师表 ...

  9. 精简高效的CSS命名准则/方法

    /* ---------------------single CSS----------------------- */ /* display */ .dn{display:none;} .di{di ...

  10. json校验

    直接百度:json在线解析  或  json.cnhttp://json.cn/ json格式校验的.这个更加简洁些.