首页 > 代码库 > jdbc 简单连接
jdbc 简单连接
package itcast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Base {
/**
* @param args
*/
public static void main(String[] args) {
}
static void template() throws Exception {
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "";
Connection conn = null;
Statement st = null;
ResultSet rs = null;
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(rs.getObject(1) + "\t" + rs.getObject(2)
+ "\t" + rs.getObject(3) + "\t" + rs.getObject(4)
+ "\t" + rs.getObject(5) + "\t");
}
} finally {
try {
if (rs != null) {
rs.close();
}
} finally {
try {
if (st != null) {
st.close();
}
} finally {
if (conn != null) {
conn.close();
}
}
}
}
}
}