本篇包括如下內容:
- ** 1,JDBC及封裝,**
- 2,DBUtil使用,
- 3,自定義連接池,
- 4,c3p0和dbcp連接池使用
1,JDBC及封裝(Java DataBase Connectivity)
-
1.1, JDBC的使用
- 注意使用前需要先引入相應的包
- 在查詢的時候用PreparedStatement這個比較安全,如果用Statement有插入攻擊的危險
try {
//1,注冊驅動
Class.forName("com.mysql.jdbc.Driver");
//2,獲取連接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ivanl?autoReconnect=true&useSSL=false&characterEncoding=utf-8", "root", "0.");
//3,通過連接進行查詢
PreparedStatement preparedStatement = connection.prepareStatement("select * from t_product");
ResultSet set = preparedStatement.executeQuery();
while(set.next()){
System.out.println(set.getString("name") + " " + set.getDouble("price"));
}
//4,關閉資源
set.close();
preparedStatement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
-
1.2, JDBC的自定義封裝
- 既然是對jdbc的封裝,也需要先引入必要的包
- 因為驅動注冊和獲取連接池以及關閉資源所有的數據庫操作都是一致的,所以驅動注冊和獲取連接池直接用靜態方法進行封裝,只讀取一次,關閉資源傳入參數進行關閉
讀取配置文件資源的時候,如果是java項目,有兩種方式:Properties和ResourceBundle,代碼有體現
package im.jdbcutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ResourceBundle;
public class JDBCUtil {
public static String driver;
public static String url;
public static String username;
public static String pwd;
static{
try {
/*
Properties properties = new Properties();
FileInputStream inputStream = new FileInputStream("src/database.properties");
properties.load(inputStream);
driver = properties.getProperty("driverClass");
url = properties.getProperty("url");
username = properties.getProperty("user");
pwd = properties.getProperty("password");
*/
ResourceBundle bundle = ResourceBundle.getBundle("database");
driver = bundle.getString("driverClass");
url = bundle.getString("url");
username = bundle.getString("user");
pwd = bundle.getString("password");
} catch (Exception e1) {
e1.printStackTrace();
}
}
public static Connection getConnection(){
try {
//1,注冊驅動
Class.forName("com.mysql.jdbc.Driver");
//2,獲取連接
return DriverManager.getConnection("jdbc:mysql://localhost:3306/ivanl?autoReconnect=true&useSSL=false&characterEncoding=utf-8", "root", "0.");
} catch (Exception e) {
System.out.println("獲取連接失敗");
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void closeAll(Connection connection, PreparedStatement statement, ResultSet resultSet){
try {
if (resultSet != null) {
resultSet.close();
}
} catch (Exception e) {
System.out.println("結果集資源釋放失敗");
e.printStackTrace();
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
System.out.println("sql聲明資源釋放失敗");
e.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (Exception e) {
System.out.println("連接集資源釋放失敗");
e.printStackTrace();
}
}
}
數據庫配置文件database.properties內容:
driverClass = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/test01?autoReconnect=true&useSSL=false&characterEncoding=utf-8
user = root
password = 0.
2,DBUtil使用(對JDBC的封裝)
DBUtil創建QueryRunner的時候有兩種方式:空參構建和數據庫構建
DBUtil有很多種類型的結果集,比如返回數組,字典,模型等等,文檔中都有比較詳細介紹,如果不太懂的話可以看一下文檔
DBUtil既然架包,那么在使用的時候必然需要先導包
-
2.1,空參構建方式,其中在執行語句的時候需要傳入連接,我這里直接使用1.2中封裝方法獲取連接,可以保證只獲取一次*
Connection connection = JDBCUtil.connection;
String sqlStr = "insert into t_ivanl001 (name, age, num) values (?, ?, ?)";
QueryRunner queryRunner = new QueryRunner();
try {
Object[] params = {name, age, num};
queryRunner.update(connection, sqlStr, params);
} catch (SQLException e) {
System.out.println("數據插入失??!");
e.printStackTrace();
}
DbUtils.closeQuietly(connection);
-
2.2,數據庫構建構建方式,構建時候需要直接傳入一個數據源,數據源可以通過c3p0或dbcp連接池獲得,這是后面的內容,這里先不涉及*
QueryRunner runner = new QueryRunner(DBCPUtil.getDataSource());
try {
List<Product> products = runner.query("select * from product", new BeanListHandler<Product>(Product.class));
System.out.println(products);
} catch (SQLException e) {
e.printStackTrace();
} finally {
}
3,自定義連接池(使用裝飾者模式進行加強)
//1,自定義連接池
/*
* 對JDBC連接的封裝,也就是自定義連接池
* 其他一些方法也需要重寫,但是不需要任何改變,所以這里就沒有貼出來
*/
public class JDBCDatasource implements DataSource {
private static LinkedList<Connection> connections = new LinkedList<Connection>();
//往連接池中添加連接
static{
for(int i=0;i<5;i++){
Connection connection = JDBCUtil.getConnection();
JDBCConnection theConnection = new JDBCConnection(connections, connection);
connections.add(theConnection);
}
}
//重寫這一個方法,如果沒有增強過connection的話,需要調用這個方法歸還連接到連接池中
@Override
public Connection getConnection() throws SQLException {
if (connections.size() == 0) {
for(int i=0;i<5;i++){
Connection connection = JDBCUtil.getConnection();
JDBCConnection theConnection = new JDBCConnection(connections, connection);
connections.add(theConnection);
}
}
return connections.removeFirst();
}
//新增一個方法
public void returnConnection(Connection connection){
connections.add(connection);
}
}
//2,自定義連接類,實現相應的方法,并在自定義的連接池中進行包裝,具體看1中的代碼
//其他一些不需要修改的覆蓋方法這里不再貼出
public class JDBCConnection implements Connection {
private Connection connection;
private LinkedList<Connection> connections;
public JDBCConnection(List<Connection> connections, Connection connection) {
this.connections = (LinkedList<Connection>) connections;
this.connection = connection;
}
//如果想要在關閉的時候添加到連接池,那么需要把連接池傳進來,傳進來最好的時候就是創建的時候
@Override
public void close() throws SQLException {
System.out.println("here here!");
connections.add(connection);
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return connection.prepareStatement(sql);
}
}
//測試
JDBCDatasource datasource = new JDBCDatasource();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = datasource.getConnection();
preparedStatement = connection.prepareStatement("select * from product;");
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
System.out.println(resultSet.getString("pname"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//這行代碼中封裝了connection.close()方法
JDBCUtil.closeAll(connection, preparedStatement, resultSet);
}
4,c3p0和dbcp連接池使用(連接池可以提高數據庫使用效率)
-
4.1,c3p0
需要導入包和配置文件
使用代碼如下:
配合DBUtils使用的時候可以直接傳入連接池進行使用,也可以傳入連接使用,見上面的DBUtils的使用
//也可以把c3p0封裝后直接獲取連接池和連接,我這里直接使用
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
DataSource dataSource = new ComboPooledDataSource();
try {
connection = dataSource.getConnection();
String sqlStr = "select * from product";
preparedStatement = connection.prepareStatement(sqlStr);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
System.out.println(resultSet.getString("pname"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCUtil.closeAll(connection, preparedStatement, resultSet);
}
-
4.2,dbcp
需要導入包和配置properties文件
使用代碼如下:
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
connection = DBCPUtil.getConnection();
try {
preparedStatement = connection.prepareStatement("select * from product");
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
System.out.println(resultSet.getString("pname"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(connection, preparedStatement, resultSet);
}
其中上面用到的DBCPUtilde封裝如下:
package im.dbcputils;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
/*
* 這里是使用默認的配置標準進行配置后讀取文件
*/
public class DBCPUtil {
private static DataSource dataSource;
static{
try {
InputStream inputStream = DBCPUtil.class.getClassLoader().getResourceAsStream("database.properties");
Properties properties = new Properties();
properties.load(inputStream);
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static DataSource getDataSource() {
return dataSource;
}
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}