1.概述
這篇文章主要說了JDBC的基本使用,包括Statement,PreparedStatement,JDBC的連接,Mysql創建用戶創建數據表,C3P0的連接與配置,DBCP的連接與配置.
2.mysql的處理
這裏的JDBC使用Mysql作爲DBMS,請先安裝Mysql,未安裝的請點擊這裏下載,安裝教程在這裏,作者使用的Mysql的8.0.17版本.
(1)新建用戶
隨便新建一個用戶,比如這裏作者新建的是aa,密碼是aa123bb.
create user 'aa'@'localhost' identified by 'aa123bb'
(2)建立數據表
建立測試用的數據表與數據庫.
create database db;
use db;
create table db
(
id int PRIMARY key,
name char(20)
);
(3)用戶權限
對剛纔新建的用戶授權:
grant select,update,delete,insert on db.* to 'aa'@'localhost';
2.JDBC
(1)jar包
(2)連接
首先註冊驅動,驅動需要一個url,用戶名和密碼,用戶名和密碼是上一步創建好的,url包含ip地址,端口和數據庫的名字.
private static final boolean mysqlVersionGreaterThen8 = true;
private static final String driver = "com.mysql" + (mysqlVersionGreaterThen8 ? ".cj" : "") + ".jdbc.Driver";
private static final String ip = "127.0.0.1";
private static final String port = "3306";
private static String databaseName = "db";
private static String url;
private static String username = "aa";
private static String password = "k041400r";
private static Connection connection = null;
public static Connection getConnection() {
try {
url = "jdbc:mysql://" + ip + ":" + port + "/" + databaseName;
Class.forName(driver);
return connection = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
這裏要注意以下舊版本的mysql的驅動叫com.mysql.jdbc.Driver,新版本的叫com.mysql.cj.jdbc.Driver.還有就是url的格式:
jdbc:mysql://ip:port/database
(3)Statement
獲取數據庫連接後,使用createStatement方法創建Statement
- 對於select,使用Statement的executeQuery(sql),返回ResultSet
- 對於update,delete,insert,使用Statement的executeUpdate(sql)
其中sql是要執行的sql語句,一個String.
public void useStatement() {
try {
useStatementInsert();
useStatementSelect();
useStatementUpdate();
useStatementSelect();
useStatementDelete();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void useStatementInsert() throws SQLException {
String sql = "insert into db(id,name) values(1,'23')";
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
}
public void useStatementDelete() throws SQLException {
String sql = "delete from db";
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
}
public void useStatementSelect() throws SQLException {
String sql = "select * from db";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int count = resultSetMetaData.getColumnCount();
while (resultSet.next()) {
for (int i = 1; i <= count; ++i) {
System.out.println(resultSet.getObject(i));
}
}
}
public void useStatementUpdate() throws SQLException {
Statement statement = connection.createStatement();
String sql = "update db set id = 3,name = '555' where id = 1";
statement.executeUpdate(sql);
}
這裏對ResultSet使用的getMetaData,可以獲取結果集的各種類型信息,包括字段的類型,個數,等等.
(4)PreparedStatement
PreparedStatement與Statement使用基本一樣.調用的時候先使用Connection的prepareStatement(sql)創建,然後
- 對於select,使用executeQuery(),返回一個ResultSet
- 對於update,delete,insert使用executeUpdate().
public void usePrepareStatement() {
try {
usePrepareStatementInsert();
usePrepareStatementSelect();
usePrepareStatementUpdate();
usePrepareStatementSelect();
usePrepareStatementDelete();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void usePrepareStatementInsert() throws SQLException {
String sql = "insert into db(id,name) values(1,'23')";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();
}
public void usePrepareStatementDelete() throws SQLException {
String sql = "delete from db";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();
}
public void usePrepareStatementSelect() throws SQLException {
String sql = "select * from db";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int count = resultSetMetaData.getColumnCount();
while (resultSet.next()) {
for (int i = 1; i <= count; ++i)
System.out.println(resultSet.getObject(i));
}
}
public void usePrepareStatementUpdate() throws SQLException {
String sql = "update db set id = 3,name = '555' where id = 1";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();
}
(5)事務
Connection有一個setAutoCommit()方法,把它設置成false即可關閉自動提交,所有語句準備好後,一次性使用commit()提交即可.
實現回滾可以配合SavePoint使用.
3.C3P0
(1)jar包
兩個:
(2)配置文件
src下創建一個叫c3p0.properties的文件:
c3p0.driverClass=com.mysql.cj.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://127.0.0.1:3306/db
c3p0.user=aa
c3p0.password=aa123bb
這裏按自己需要更改即可.
(3)工具類
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
public class DbUtil
{
private static ComboPooledDataSource C3P0dataSource = new ComboPooledDataSource("c3p0.properties");
public static void releaseConnection(Connection connection)
{
try
{
if(connection != null)
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static Connection getC3P0Connection()
{
try
{
return C3P0dataSource.getConnection();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
4.DBCP
(1)jar包
三個:
(2)配置文件
src下新建dbcp.properties:
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db
username=aa
password=k041400r
initialSize=10
maxActive=50
maxIdle=15
minIdle=10
maxWait=60000
connectionProperties=useUnicode=true;characterEncoding=utf8
defaultAutoCommit=true
分別是驅動,url,用戶名,密碼,初始化連接數,最大連接數,最大空閒連接數,最小空閒連接數,最大等待實際,連接屬性(這裏設置了編碼),自動提交.
(3)工具類
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
import javax.sql.DataSource;
public class DbUtil {
private static DataSource DBCPdataSource;
static {
try {
InputStream inputStream = DbUtil.class.getClassLoader().getResourceAsStream("dbcp.properties");
Properties properties = new Properties();
properties.load(inputStream);
DBCPdataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getDBCPConnection() {
try {
return DBCPdataSource.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void releaseConnection(Connection connection) {
try {
if (connection != null)
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
首先加載屬性文件,再使用Properties的load方法將其加載到一個Properties對象中,最後交給BasicDataSourceFactory處理.
5.源碼
包含了jar包,配置文件,sql文件與測試代碼.