package utsc.java.jdbc.DBUtil.utils;
import java.sql.*;
public class DBUtil {
private DBUtil(){}
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/imooc","root","123456");
}
public static void close(Connection conn, Statement ps, ResultSet rs){
if (rs !=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps !=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn !=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package utsc.java.jdbc.DBUtil;
import utsc.java.jdbc.DBUtil.utils.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCTest12 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
String sql = "select ename from emp where ename like?";
ps = conn.prepareStatement(sql);
ps.setString(1,"_A%");
rs = ps.executeQuery();
while (rs.next()){
System.out.println(rs.getString("ename"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(conn,ps,rs);
}
}
}