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 final class JdbcUtils {
private static String url="jdbc:mysql://localhost:3306/jdbc";
private static String user = "root";
private static String password = "sql1";
private JdbcUtils(){
}
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection(){
try {
return DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
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();
}
}
}
}
}
}
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) throws SQLException, ClassNotFoundException{
template();
}
static void template() throws SQLException{
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
st = conn.createStatement();
rs = st.executeQuery("select * from user");
while(rs.next()){
System.out.println(rs.getObject(1)+"\t"+rs.getObject(2)+"\t");
}
}finally{
JdbcUtils.free(rs, st, conn);
}
}
static void test() throws SQLException, ClassNotFoundException{
//1.register dbdriver method1
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//method2
// System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");
//method3
// Class.forName("com.mysql.jdbc.Driver");
//2.connect to db
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc","root","sql1");
// url = "jdbc:mysql:///jdbc";//this format is also right for the localhost:3306 connect
//3.create statment
Statement st = conn.createStatement();
//4.execute statement
ResultSet rs = st.executeQuery("select * from user");
//5.handle the result
while(rs.next()){
System.out.println(rs.getObject(1)+"\t"+
rs.getObject(2)+"\t"+rs.getObject(3)+"\t"+rs.getObject(4));
}
//6.release resource
rs.close();
st.close();
conn.close();
}
}