1 注册驱动(只做一次)mysql文档找驱动的名字
2 建立连接(Connection)
3 创建SQL的语句(Statement)
4 执行语句
5 处理执行结果(ResultSet)
6 释放资源
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
/**
*
* @author leiwei
* 测试类
*
*/
public class JDBCTest {
public static void main(String[] args) throws Exception {
template();
}
// 模板代码
static void template() throws Exception {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
// create connection
conn = JDBCUtil.getConnection();
// create statement
st = conn.createStatement();
// run statement
rs = st.executeQuery("select * from user");
// handle result
while (rs.next()) {
System.out.println(rs.getObject(1) + "\t" + rs.getObject(2)
+ "\t" + rs.getObject(3) + "\t");
}
// 释放资源
} finally {
JDBCUtil.free(rs, st, conn);
}
}
}
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
*
* @author leiwei
* 工具类 不允许被继承
*
*/
public final class JDBCUtil {
private static String driverClassName = ""; //驱动
private static String url = ""; //数据库地址
private static String user = ""; //用户名
private static String password = ""; //密码
// 不能构造实例
private JDBCUtil() {}
//静态代码块只会被执行一次 可以用来注册驱动
static {
try {
InputStream in = JDBCUtil.class.getResourceAsStream("/jdbc.properties");
Properties prop = prop = new Properties();
prop.load(in);
driverClassName = prop.getProperty("jdbc.mysql.driverClassName");
url = prop.getProperty("jdbc.mysql.url");
user = prop.getProperty("jdbc.mysql.username");
password = prop.getProperty("jdbc.mysql.password");
Class.forName(driverClassName);//根据类名转载类
System.out.println("url地址:"+url+"\n用户名username:"+user+"\n密码password:"+password);
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
} catch (IOException e) {
e.printStackTrace();
}
}
// create connection
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();
}
}
}
}
}
}
jdbc.properties
jdbc.mysql.driverClassName=com.mysql.jdbc.Driver
jdbc.mysql.url=jdbc:mysql://172.18.95.19:3306/bank
jdbc.mysql.username=test
jdbc.mysql.password=test