##mainTest.java
package com.itheima.test;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.Driver;
public class mainTest {
public static void main(String[] args) {
try {
//1.注册驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//2.建立连接 参数一:协议+访问的数据库 ,参数二:用户名 , 参数三:密码。
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/student", "root", "root");
//3.创建statement ,跟数据库打交 ,一定需要这个对象
Statement st = conn.createStatement();
//4.执行查询 ,得到结果集
String sql = "select * from t_stu";
ResultSet rs = st.executeQuery(sql);
//5.遍历查询每一条记录
while(rs.next()) {
int id = rs.getInt("id");
String name=rs.getString("name");
int age = rs.getInt("age");
System.out.println("id="+id +"===name="+name+"==age="+age);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtil.release(conn, st, rs);
}
}
}
##jdbcUtil.java
package com.itheima.Util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtil {
/**
* 6.释放资源
* @param conn
* @param st
* @param rs
*/
public static void release(Connection conn , Statement st , ResultSet rs) {
closeRs(rs);
closeSt(st);
closeConn(conn);
}
private static void closeRs(ResultSet rs) {
try {
if(rs != null) {
rs.close();
}
}catch (SQLException e) {
e.printStackTrace();
}finally {
rs = null;
}
}
private static void closeSt(Statement st) {
try {
if(st != null) {
st.close();
}
}catch (SQLException e) {
e.printStackTrace();
}finally {
st = null;
}
}
private static void closeConn(Connection conn) {
try {
if(conn != null) {
conn.close();
}
}catch (SQLException e) {
e.printStackTrace();
}finally {
conn = null;
}
}
}