ITeye博客

通用jdbc链接-mysql

breezedancer · 2007-05-28 09:00 · java/j2ee · 企业架构 · Markdown

java 代码

  1. package com.com.util;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. public class DBConn {
  8. private Connection conn = null;
  9. Statement statement = null;
  10. ResultSet rs = null;
  11. public DBConn() {
  12. try {
  13. Class.forName("com.mysql.jdbc.Driver");// 加载驱动程序
  14. conn = DriverManager.getConnection(
  15. "jdbc:mysql://localhost/actions", "admin", "111111");
  16. statement = conn.createStatement();
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. conn = null;
  20. }
  21. }
  22. public DBConn(String dbname) {
  23. try {
  24. Class.forName("com.mysql.jdbc.Driver");// 加载驱动程序
  25. String url = "jdbc:mysql://localhost/" + dbname;
  26. conn = DriverManager.getConnection(url, "admin", "111111");
  27. statement = conn.createStatement();
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. conn = null;
  31. }
  32. }
  33. public void update(String sql) {
  34. try {
  35. statement.executeUpdate(sql);
  36. } catch (SQLException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. public ResultSet query(String sql) {
  41. ResultSet rs = null;
  42. try {
  43. rs = statement.executeQuery(sql);
  44. } catch (SQLException e) {
  45. e.printStackTrace();
  46. }
  47. return rs;
  48. }
  49. public void close() {
  50. try {
  51. if (rs != null) {
  52. rs.close();
  53. rs = null;
  54. }
  55. if (statement != null) {
  56. statement.close();
  57. statement = null;
  58. }
  59. if (conn != null) {
  60. conn.close();
  61. conn = null;
  62. }
  63. } catch (Exception e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. }

评论(1)

  1. #1 楼 · yyjn12 · 2007-05-28 09:10

    不错,挺好的.学习!

评论功能维护中,当前仅展示历史评论。