package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Base {
public static void main(String[] args) {
try {
template();
} catch (Exception e) {
e.printStackTrace();
}
}
static void template() throws Exception {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/jdbc";
String user = "root";
String password = "123456";
try {
// 1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.建立连接
conn = DriverManager.getConnection(url, user, password);
// 3.创建语句
st = conn.createStatement();
// 4.执行语句
rs = st.executeQuery("select * from user");
// 5.处理结果
while (rs.next()) {
System.out.println("id:" + rs.getObject(1) + "\tname:"
+ rs.getObject(2) + "\tbirthday:" + rs.getObject(3)
+ "\tmoney:" + rs.getObject(4));
}
// 6.释放资源
} finally {
try {
if (rs != null)
rs.close();
} finally {
try {
if (st != null)
st.close();
} finally {
if (conn != null)
conn.close();
}
}
}
}
}
这是一个比较完整的以mysql为例子的连接数据库的代码。
缺点:
- 每进行一次连接就注册一次驱动,
- 释放资源部分代码繁琐。
可以对这个例子进行简单升级对连接数据库的简单升级