MySQL数据库连接工具
(一)MySQL数据库连接工具【原始JDBC封装后的数据库连接工具】
(二)MySQL数据库连接工具【Hibernate框架的数据库连接工具】
(一)MySQL数据库连接工具【原始JDBC封装后的数据库连接工具】
Business.java
package com.hk.server.base;
import java.sql.*;
/**
* Business 类
*
* 用于实现和数据库的连接
*
* @author: shipleyleo
* @create: 2023-05-19 18:29:08
*/
public class Business {
// 加载驱动,创建连接,释放资源
private static final String driver = "com.mysql.cj.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/hk";
private static final String username = "root";
private static final String pwd = "******";
static {
try {
Class.forName(driver); // 加载驱动
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection(url, username, pwd); // 建立数据库连接对象
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void release (ResultSet rs, Statement stmt, Connection con) {
try {
if(rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if(stmt != null) {
stmt.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if(con != null) {
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
if(rs == null) {
System.out.println("rs==null"+"util"); // 断开某会话连接
}
}
public static void release (Object o) {
try {
if (o instanceof ResultSet) {
((ResultSet) o).close();
} else if (o instanceof Statement) {
((Statement) o).close();
} else if (o instanceof Connection) {
((Connection) o).close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void printRs (ResultSet rs) {
if(rs == null) {
return;
}
try {
ResultSetMetaData md = rs.getMetaData();
int column = md.getColumnCount();
StringBuffer sb = new StringBuffer();
for(int i=1; i<=column; i++) {
sb.append(md.getColumnName(i) + "\t");
}
sb.append("\n");
while(rs.next()) {
for(int i=1; i<=column; i++) {
sb.append(rs.getString(i) + "\t");
}
sb.append("\n");
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException {
// 1、获取数据库连接
Connection con = Business.getConnection();
// 2、建立操作对象
Statement stmt = con.createStatement();
// 3、结果集
ResultSet rs = stmt.executeQuery("select * from User");
// 打印结果
Business.printRs(rs);
// 4、释放连接
Business.release(rs,stmt,con);
}
}
附录
数据库建表脚本(MySQL):
CREATE TABLE `user` ( `oid` bigint(20) NOT NULL COMMENT '网点 ID', `name` varchar(12) DEFAULT NULL COMMENT '网点名称', `passwd` varchar(12) DEFAULT NULL COMMENT '网点密码', `city` varchar(20) DEFAULT NULL COMMENT '城市', `address` varchar(20) DEFAULT NULL COMMENT '地址', PRIMARY KEY (`oid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
执行工具类的 main() 方法,输出结果:
相关文章