1.创建一个工具类
2.通过工具类来实现jdbc中的某些步骤。
具体见代码。
工具类:JdbcUtils
package com.weixuan.project;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 这是一个工具类 不需要继承----设为final 不需要创建实例---将构造函数设为私有
*
* @author 韦轩
*
*/
public final class JdbcUtils {
private static String url = "jdbc:mysql://localhost:3306/test";
private static String user = "root";
private static String password = "root";
private JdbcUtils() {
}
// 静态的代码块,用来处理注册驱动,保证注册只做一次
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// 这个异常不能简单的catch,要专门处理
throw new ExceptionInInitializerError(e);
}
}
// 将链接也只做一次。
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void free(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
模板类:JdbcTemplate
package com.weixuan.project;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTemplate {
static Connection conn = null;
static Statement st = null;
static ResultSet rs = null;
static void test() throws SQLException {
// 调用工具类的接口,注册驱动已经做了。
try {
conn = JdbcUtils.getConnection();
// 创建语句
st = conn.createStatement();
// 执行语句
rs = st.executeQuery("select * from mytable");
// 处理结果
while (rs.next()) {
System.out.println(rs.getObject(1) + "\t" + rs.getObject(2)
+ "\t" + rs.getObject(3) + "\t");
}
} finally {
// 释放资源
JdbcUtils.free(rs, st, conn);
}
}
//测试
public static void main(String[] args) {
try {
new JdbcTemplate().test();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
执行结果:
数据库信息: