JDBCUtils
注意:
- 声明全局变量后,静态代码块里边的变量不要再声明!
- new RuntimeException(e)
可以将编译异常转换为运行时异常,不再编译报错。使代码简洁。。
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* 此类是封装JDBC连接的工具类
*
*功能:1、获取连接;
* 2、释放资源。
*
*/
public class JDBCUtils {
//声明全局变量后,静态代码块里边的变量不要再声明!
static String user;
static String password;
static String url;
static String driver;
static {
Properties info = new Properties();
try {
info.load(new FileInputStream("src\\jdbc.properties.properties"));
} catch (IOException e) {
e.printStackTrace();
}
user = info.getProperty("user");
password = info.getProperty("password");
url = info.getProperty("url");
driver = info.getProperty("driver");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 功能:获取可用的连接对象
* @return 连接
* @throws Exception
*/
public static Connection getConnection() {
// Connection connection = DriverManager.getConnection(url, user, password);
// return connection;
//将编译异常转换为运行时异常,不再编译报错。使代码简洁。。
try {
return DriverManager.getConnection(url, user, password);
} catch (Exception e) {
throw new RuntimeException(e);//运行时异常
}
}
/**
* 功能:释放资源
* @param set
* @param statement
* @param connection
* @throws Exception
*/
public static void close(ResultSet set, PreparedStatement statement,Connection connection) throws Exception{
if(set!=null){
set.close();
}
if(statement!=null){
statement.close();
}
if(connection!=null){
connection.close();
}
}
}
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class JDBCPractice1ByUtils {
public static void main(String[] args) throws Exception{
// 查询生日晚于98年的女生信息。
//1.获取连接
Connection connection = JDBCUtils.getConnection();
//2.执行查询
String sql = "SELECT * FROM beauty WHERE year(borndate) <1998";
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet set = ps.executeQuery();
while (set.next()) {
int id = set.getInt("id");
String name = set.getString("name");
System.out.println(id+"\t"+name);
}
//3.关闭
JDBCUtils.close(set,ps,connection);
}
}
用try catch finally包围起来。
import java.sql.*;
public class JDBCPractice2ByUtils {
public static void main(String[] args) throws Exception {
// 查询生日晚于98年的女生信息。
Connection connection = null;
PreparedStatement ps = null;
ResultSet set = null;
try {
//1.获取连接
connection = JDBCUtils.getConnection();
//2.执行查询
String sql = "SELECT * FROM beauty WHERE year(borndate) <1998";
ps = connection.prepareStatement(sql);
set = ps.executeQuery();
while (set.next()) {
int id = set.getInt("id");
String name = set.getString("name");
System.out.println(id + "\t" + name);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//3.关闭
JDBCUtils.close(set, ps, connection);
}
}
}