通用jdbc链接-mysql

java 代码
  1. package com.com.util;   
  2.   
  3. import java.sql.Connection;   
  4. import java.sql.DriverManager;   
  5. import java.sql.ResultSet;   
  6. import java.sql.SQLException;   
  7. import java.sql.Statement;   
  8.   
  9. public class DBConn {   
  10.   
  11.     private Connection conn = null;   
  12.   
  13.     Statement statement = null;   
  14.   
  15.     ResultSet rs = null;   
  16.   
  17.     public DBConn() {   
  18.         try {   
  19.             Class.forName("com.mysql.jdbc.Driver");// 加载驱动程序   
  20.             conn = DriverManager.getConnection(   
  21.                     "jdbc:mysql://localhost/actions""admin""111111");   
  22.             statement = conn.createStatement();   
  23.         } catch (Exception e) {   
  24.             e.printStackTrace();   
  25.             conn = null;   
  26.         }   
  27.     }   
  28.   
  29.     public DBConn(String dbname) {   
  30.         try {   
  31.             Class.forName("com.mysql.jdbc.Driver");// 加载驱动程序   
  32.             String url = "jdbc:mysql://localhost/" + dbname;   
  33.             conn = DriverManager.getConnection(url, "admin""111111");   
  34.             statement = conn.createStatement();   
  35.         } catch (Exception e) {   
  36.             e.printStackTrace();   
  37.             conn = null;   
  38.         }   
  39.     }   
  40.   
  41.     public void update(String sql) {   
  42.         try {   
  43.             statement.executeUpdate(sql);   
  44.         } catch (SQLException e) {   
  45.             e.printStackTrace();   
  46.         }   
  47.     }   
  48.   
  49.     public ResultSet query(String sql) {   
  50.         ResultSet rs = null;   
  51.         try {   
  52.             rs = statement.executeQuery(sql);   
  53.         } catch (SQLException e) {   
  54.             e.printStackTrace();   
  55.         }   
  56.         return rs;   
  57.     }   
  58.   
  59.     public void close() {   
  60.         try {   
  61.             if (rs != null) {   
  62.                 rs.close();   
  63.                 rs = null;   
  64.             }   
  65.   
  66.             if (statement != null) {   
  67.                 statement.close();   
  68.                 statement = null;   
  69.             }   
  70.   
  71.             if (conn != null) {   
  72.                 conn.close();   
  73.                 conn = null;   
  74.             }   
  75.   
  76.         } catch (Exception e) {   
  77.             e.printStackTrace();   
  78.         }   
  79.     }   
  80. }   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值