1、为了使JDBC用起来更加的方便,进行MyJDBCUtils的包装,利用MyJDBCUtils对外提供,操作数据的方法
2、MyJDBCUtils的代码如下
package com.jdbc.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MyJDBCUtils {
static String url = "jdbc:mysql://localhost:3306/testdatabase";
static String username = "root";
static String password = "1234";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
throw new RuntimeException("获取连接Mysql数据库连接失败");
}
return conn;
}
public static void release(Connection conn, Statement st, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
throw new RuntimeException("ResultSet关闭异常");
}
rs = null;
}
if (st != null) {
try {
st.close();
} catch (Exception e) {
throw new RuntimeException("Statement关闭异常");
}
st = null;
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
throw new RuntimeException("Connection关闭异常");
}
conn = null;
}
}
}
3、使用MyJDBCUtils进行Mysql的访问代码如下
package com.jdbc.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
public class TestMyJDBCUtils {
@Test
public void testMyJDBCUtils() {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = MyJDBCUtils.getConnection();
st = conn.createStatement();
rs = st.executeQuery("select * from user ");
while (rs.next()) {
int id = rs.getInt(rs.findColumn("id"));
String uname = rs.getString(rs.findColumn("uname"));
int age = rs.getInt(rs.findColumn("age"));
// 遍历输出
System.out.println("id " + id + " " + "uname " + uname + " "
+ "age " + age + " ");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// 释放资源
MyJDBCUtils.release(conn, st, rs);
}
}
}