這篇文章主要說了JDBC的基本使用,包括Statement,PreparedStatement,JDBC的鏈接,Mysql建立用戶建立數據表,C3P0的鏈接與配置,DBCP的鏈接與配置.html
這裏的JDBC使用Mysql做爲DBMS,請先安裝Mysql,未安裝的請點擊這裏下載,安裝教程在這裏,做者使用的Mysql的8.0.17版本.java
隨便新建一個用戶,好比這裏做者新建的是aa,密碼是aa123bb.mysql
create user 'aa'@'localhost' identified by 'aa123bb'
創建測試用的數據表與數據庫.git
create database db; use db; create table db ( id int PRIMARY key, name char(20) );
對剛纔新建的用戶受權:github
grant select,update,delete,insert on db.* to 'aa'@'localhost';
8.0.17版本在這裏sql
各個版本的在這裏下載數據庫
首先註冊驅動,驅動須要一個url,用戶名和密碼,用戶名和密碼是上一步建立好的,url包含ip地址,端口和數據庫的名字.apache
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的格式:maven
jdbc:mysql://ip:port/database
獲取數據庫鏈接後,使用createStatement方法建立Statementide
其中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,能夠獲取結果集的各類類型信息,包括字段的類型,個數,等等.
PreparedStatement與Statement使用基本同樣.調用的時候先使用Connection的prepareStatement(sql)建立,而後
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(); }
Connection有一個setAutoCommit()方法,把它設置成false便可關閉自動提交,全部語句準備好後,一次性使用commit()提交便可. 實現回滾能夠配合SavePoint使用.
兩個:
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
這裏按本身須要更改便可.
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; } }
三個:
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,用戶名,密碼,初始化鏈接數,最大鏈接數,最大空閒鏈接數,最小空閒鏈接數,最大等待實際,鏈接屬性(這裏設置了編碼),自動提交.
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處理.
包含了jar包,配置文件,sql文件與測試代碼.