JDBC 學習心得總結
阿新 • • 發佈:2019-02-05
資料庫連線:學習JDBC的主要步驟有:
1) 這是最原始的連結方法:
String userName = "root";
String password = "";
String url = "jdbc:mysql://localhost:3306/mysqltest?useUnicode=true&characterEncoding=gbk";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
public Dao() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
} catch (Exception e) {
e.printStackTrace();
System.out.println("連結失敗");
}
}
2)
//這種方法與下面的方法的不同之處就在於:這種方法的連結的四個字串是在類裡面賦值的,
//而下面的方法是從 jdbc.properties 配置檔案中獲取的
public void testDriver() throws SQLException {
Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/test";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "");
Connection connection = (Connection) driver.connect(url, info);
System.out.println(connection);
3) 參考:jdbc_expression1.Jdbc
//首先從properties檔案裡獲取了資源放在 properties例項裡面,
//再通過Driver driver = (Driver) Class.forName(driverClass).newInstance();
//來獲取Driver例項,
//傳參給driver後就可以通過driver.connection(url,Info)得到 Connection 例項
public Connection getConnection() throws Exception {
String driverClass = null;
String url = null;
String userName = null;
String password = null;
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
url = properties.getProperty("url");
userName = properties.getProperty("userName");
password = properties.getProperty("password");
Driver driver = (Driver) Class.forName(driverClass).newInstance();
Properties info = new Properties();
info.put("user", userName);
info.put("password", password);
Connection connection = (Connection) driver.connect(url, info);
return connection;
}
4)參考:Jcbc_connedtion.JdbcTools
//通過class.forName(driverClass)來載入
public Connection getConnection2()throws Exception{
String driverClass = null;
String url = null;
String userName = null;
String password = null;
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
url = properties.getProperty("url");
userName = properties.getProperty("userName");
password = properties.getProperty("password");
Class.forName("driverClass");
Connection connection=(Connection) DriverManager.getConnection(url,userName,password);
return connection;
}
5)參考:jdbc_connection.JdbcTools
ComboPooledDataSource()獲取了src 目錄下的c3p0-config.xml檔案 裡面的“helloc3p0”的內容
來建立Datasource例項,再有dataSource 獲取 connection 例項
private static DataSource dataSource=null;
static{
dataSource=new ComboPooledDataSource("helloc3p0");
}
public static Connection getConnectionByPool() throws SQLException{
return dataSource.getConnection();
6)參考:controller.Batch_processed
/**
* 使用資料庫連線池:
* @throws SQLException
*
*
*
*/
@Test
public void testDBCP() throws SQLException{
BasicDataSource dataSource=null;
dataSource=new BasicDataSource();
dataSource.setUsername("root");
dataSource.setPassword("");
dataSource.setUrl("jdbc:mysql:///test");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setInitialSize(10);
dataSource.setMinIdle(5);
dataSource.setMaxWaitMillis(5000);;
Connection connection=dataSource.getConnection();
System.out.println(connection.getClass());
}
7)
參考:.controller.Batch_processed
/**
* 使用工廠模式來建立BasicDataSource,從而建立連線connection
*
* @throws Exception
*/
@Test
public void testDBCPBasicDataSourceFactory() throws Exception{
Properties properties=new Properties();
InputStream inputStream=Batch_processed.class.getClassLoader().
getResourceAsStream("dbcp.properties");
properties.load(inputStream);
DataSource dataSource=BasicDataSourceFactory.createDataSource(properties);
BasicDataSource basicDataSource=(BasicDataSource) dataSource;
System.out.println(dataSource.getConnection());
------------------------------------------------------
2、獲取statement;
Statement=connection.createStatement();
preparedStatement=connection.preparedStatement();
1)如果是用statement的話就直接拼寫 sql 語句:
2)用 preparedStatement就用setObject(int,Object);
--------------------------------------------------------
3、獲取並處理結果集
1); 由結果集轉換為bean
//該方法用例 DBUtiles.jar 包中的 import org.apache.commons.dbutils.handlers.BeanHandler/QueryRunner;
Location :Jdbc_practice.bean.BeanUtilTest.java
QueryRunner queryRunner=new QueryRunner();
@Test
public void testBeanHandler(){
Connection connection=null;
try {
connection=JdbcTools.getConnectionByPool();
String sql="select * from book where id=?";
Book book= queryRunner.query(connection, sql, new BeanHandler<Book>(Book.class), 5);
System.out.println(book);
} catch (Exception e) {
e.printStackTrace();
}finally{
JdbcTools.release(null, null, connection);
}
}
2)這是個狹隘的方法:只能用在特定的bean類;
public List<Book> getAllBook2()throws Exception{
List<Book> list=new ArrayList<Book>();
Book book=null;
String sql="select * from book";
Connection connection=JdbcTools.getConnection();
PreparedStatement preparedStatement=(PreparedStatement) connection.prepareStatement(sql);
ResultSet resultSet=preparedStatement.executeQuery();
while(resultSet.next()){
book=new Book();
book.setNumber(resultSet.getInt(1));
book.setBookName(resultSet.getString(2));
book.setAuthor(resultSet.getString(3));
book.setPrice(resultSet.getInt(4));
list.add(book);
}
return list;
}
3) 這是個通用方法:實現方法有兩個:(1)通過java反類來實現,(2)通過DBUtils的靜態方法
setProperty(T,fieldName,fieldValue)來實現;具體參考.bean.BeanUtileTest
public static <T>T getObject(Class<T> clazz,String sql,Object ... args )throws Exception{
T entity =null;
Connection connection=JdbcTools.getConnection();
PreparedStatement preparedStatement=(PreparedStatement) connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
preparedStatement.setObject(i+1, args[i]);
}
ResultSet resultSet=preparedStatement.executeQuery();
Map<String, Object>values=new HashMap<String, Object>();
ResultSetMetaData resultSetMetaData=resultSet.getMetaData();
while(resultSet.next()){
for(int i=0;i<resultSetMetaData.getColumnCount();i++){
String columLabel = resultSetMetaData.getColumnLabel(i+1);
Object columValue = resultSet.getObject(columLabel);
values.put(columLabel,columValue);
}
}
if(values.size()>0){
entity=clazz.newInstance();
java.lang.reflect.Field[] field=entity.getClass().getDeclaredFields();
System.out.println("for before");
for(Map.Entry<String,Object>entry : values.entrySet()){
String fieldName=entry.getKey();
Object fieldValue=entry.getValue();
//使用BeanUtils.setProperty(),功能和註釋部分一樣
BeanUtils.setProperty(entity, fieldName, fieldValue);
// for(int i=0;i<field.length;i++){
// field[i].setAccessible(true);
// try {
// if(field[i].getType().equals(String.class)){
// if(field[i].getName().equals(fieldName)){
// field[i].set(entity, fieldValue);
// }
// }else if(field[i].getType().equals(int.class)){
// if(field[i].getName().equals(fieldName)){
// field[i].set(entity, fieldValue);
// }
// }
// } catch (Exception e) {
// field[i].setAccessible(true);
// }
// }
}
}
return entity;
}
/**
* 這個方法的實現跟上面的差不多;
* 這是將結果集轉化為 List<T> 的方法
*/
public static <T> List<T> getObjects(Class<T> clazz,String sql,Object ... args)
throws Exception{
T entity=null;
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
List<Map<String, Object>>list=new ArrayList<Map<String,Object>>();
List<T>listObject=new ArrayList<T>();
try{
connection=JdbcTools.getConnection();
preparedStatement=(PreparedStatement) connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
preparedStatement.setObject(i+1, args[i]);
}
resultSet=preparedStatement.executeQuery();
ResultSetMetaData resultSetMetaData=resultSet.getMetaData();
while(resultSet.next()){
Map<String,Object>values=new HashMap<String,Object>();
for(int i=0;i<resultSetMetaData.getColumnCount();i++){
String columLable=resultSetMetaData.getColumnLabel(i+1);
Object columValue=resultSet.getObject(i+1);
values.put(columLable, columValue);
}
list.add(values);
}
}catch (Exception e) {
e.printStackTrace();
}finally{
JdbcTools.release(resultSet, preparedStatement, connection);
}
if(!list.isEmpty()){
Iterator<Map<String, Object>> iterator=list.iterator();
while(iterator.hasNext()){
entity=clazz.newInstance();
java.lang.reflect.Field[] field=entity.getClass().getDeclaredFields();
Map<String,Object>values=iterator.next();
for(Map.Entry<String,Object>entry:values.entrySet()){
String fieldName=entry.getKey();
Object fieldValue=entry.getValue();
for(int i=0;i<field.length;i++){
field[i].setAccessible(true);
if(field[i].getType().equals(String.class)){
if(field[i].getName().equals(fieldName)){
field[i].set(entity, fieldValue);
}
}else if(field[i].getType().equals(int.class)){
if(field[i].getName().equals(fieldName)){
field[i].set(entity, fieldValue);
}
}
}
}
listObject.add(entity);
}
}
return listObject;
}
----------------------------------------------------------------------------------------
4、關閉資源;
//參考:jdbc_connection.JdbcTools
public static void release(ResultSet resultSet,Statement statement,Connection connection){
if(resultSet!=null){
try {
resultSet.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(statement!=null){
try {
statement.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(connection!=null){
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
}
----------------------------------------------------------------------------------
5、批量處理:
//參考 :controller.Batch_processed
/**
*
* 批處理
* 電腦不穩定測試難
*
* @throws Exception
*/
@Test
public void testBatch() throws Exception{
Connection connection=null;
java.sql.PreparedStatement preparedStatement=null;
String sql="insert into customers values(?,?,?)";
try {
connection=JdbcTools.getConnection();
JdbcTools.beginTransaction(connection);
preparedStatement=connection.prepareStatement(sql);
long begin=System.currentTimeMillis();
for(int i=0;i<10000;i++){
//核心程式碼
preparedStatement.setInt(1, i+1);
preparedStatement.setString(2, "name_"+i);
preparedStatement.setString(3, "2016-8-6");
preparedStatement.addBatch();
if((i%300)==0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
}
if(10000%300!=0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
JdbcTools.commit(connection);
long end=System.currentTimeMillis();
System.out.println(end-begin);//5281
} catch (Exception e) {
e.printStackTrace();
JdbcTools.rollback(connection);
}finally{
JdbcTools.release(preparedStatement, connection);
}
}
--------------------------------------------------------------------------------
6、事務處理;
//參考:controller.transactionTest
/**
* 資料庫隔離事務--READ_COMMITED 和 READ_UNCOMMITED 的區別
* 測試用例
*
*
*/
@Test
public void testTransactionIsolutionUpdate(){
Connection connection = null;
try {
connection =JdbcTools.getConnection();
connection.setAutoCommit(false);
String sql="update book set price=price+100 where id=9";
update(connection, sql);
//connection.commit();先提交再讀取
//讀取未提交的資料
String sql1="select price from book where id=9";
int price =(int)getSingleColum(sql1);
System.out.println(price);
connection.commit();//先讀取再提交
} catch (Exception e) {
e.printStackTrace();
}finally{
JdbcTools.release(null,null,connction);
}
}
1、資料庫連線:
資料庫連線有多種方法:1) 這是最原始的連結方法:
String userName = "root";
String password = "";
String url = "jdbc:mysql://localhost:3306/mysqltest?useUnicode=true&characterEncoding=gbk";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
public Dao() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
} catch (Exception e) {
e.printStackTrace();
System.out.println("連結失敗");
}
}
2)
//這種方法與下面的方法的不同之處就在於:這種方法的連結的四個字串是在類裡面賦值的,
//而下面的方法是從 jdbc.properties 配置檔案中獲取的
public void testDriver() throws SQLException {
Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/test";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "");
Connection connection = (Connection) driver.connect(url, info);
System.out.println(connection);
}
//首先從properties檔案裡獲取了資源放在 properties例項裡面,
//再通過Driver driver = (Driver) Class.forName(driverClass).newInstance();
//來獲取Driver例項,
//傳參給driver後就可以通過driver.connection(url,Info)得到 Connection 例項
public Connection getConnection() throws Exception {
String driverClass = null;
String url = null;
String userName = null;
String password = null;
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
url = properties.getProperty("url");
userName = properties.getProperty("userName");
password = properties.getProperty("password");
Driver driver = (Driver) Class.forName(driverClass).newInstance();
Properties info = new Properties();
info.put("user", userName);
info.put("password", password);
Connection connection = (Connection) driver.connect(url, info);
return connection;
}
4)參考:Jcbc_connedtion.JdbcTools
//通過class.forName(driverClass)來載入
public Connection getConnection2()throws Exception{
String driverClass = null;
String url = null;
String userName = null;
String password = null;
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
url = properties.getProperty("url");
userName = properties.getProperty("userName");
password = properties.getProperty("password");
Class.forName("driverClass");
Connection connection=(Connection) DriverManager.getConnection(url,userName,password);
return connection;
}
5)參考:jdbc_connection.JdbcTools
ComboPooledDataSource()獲取了src 目錄下的c3p0-config.xml檔案 裡面的“helloc3p0”的內容
來建立Datasource例項,再有dataSource 獲取 connection 例項
private static DataSource dataSource=null;
static{
dataSource=new ComboPooledDataSource("helloc3p0");
}
public static Connection getConnectionByPool() throws SQLException{
return dataSource.getConnection();
}
6)參考:controller.Batch_processed
/**
* 使用資料庫連線池:
* @throws SQLException
*
*
*
*/
@Test
public void testDBCP() throws SQLException{
BasicDataSource dataSource=null;
dataSource=new BasicDataSource();
dataSource.setUsername("root");
dataSource.setPassword("");
dataSource.setUrl("jdbc:mysql:///test");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setInitialSize(10);
dataSource.setMinIdle(5);
dataSource.setMaxWaitMillis(5000);;
Connection connection=dataSource.getConnection();
System.out.println(connection.getClass());
}
7)
參考:.controller.Batch_processed
/**
* 使用工廠模式來建立BasicDataSource,從而建立連線connection
*
* @throws Exception
*/
@Test
public void testDBCPBasicDataSourceFactory() throws Exception{
Properties properties=new Properties();
InputStream inputStream=Batch_processed.class.getClassLoader().
getResourceAsStream("dbcp.properties");
properties.load(inputStream);
DataSource dataSource=BasicDataSourceFactory.createDataSource(properties);
BasicDataSource basicDataSource=(BasicDataSource) dataSource;
System.out.println(dataSource.getConnection());
------------------------------------------------------
2、獲取statement;
Statement=connection.createStatement();
preparedStatement=connection.preparedStatement();
1)如果是用statement的話就直接拼寫 sql 語句:
2)用 preparedStatement就用setObject(int,Object);
--------------------------------------------------------
3、獲取並處理結果集
1); 由結果集轉換為bean
//該方法用例 DBUtiles.jar 包中的 import org.apache.commons.dbutils.handlers.BeanHandler/QueryRunner;
Location :Jdbc_practice.bean.BeanUtilTest.java
QueryRunner queryRunner=new QueryRunner();
@Test
public void testBeanHandler(){
Connection connection=null;
try {
connection=JdbcTools.getConnectionByPool();
String sql="select * from book where id=?";
Book book= queryRunner.query(connection, sql, new BeanHandler<Book>(Book.class), 5);
System.out.println(book);
} catch (Exception e) {
e.printStackTrace();
}finally{
JdbcTools.release(null, null, connection);
}
}
2)這是個狹隘的方法:只能用在特定的bean類;
public List<Book> getAllBook2()throws Exception{
List<Book> list=new ArrayList<Book>();
Book book=null;
String sql="select * from book";
Connection connection=JdbcTools.getConnection();
PreparedStatement preparedStatement=(PreparedStatement) connection.prepareStatement(sql);
ResultSet resultSet=preparedStatement.executeQuery();
while(resultSet.next()){
book=new Book();
book.setNumber(resultSet.getInt(1));
book.setBookName(resultSet.getString(2));
book.setAuthor(resultSet.getString(3));
book.setPrice(resultSet.getInt(4));
list.add(book);
}
return list;
}
3) 這是個通用方法:實現方法有兩個:(1)通過java反類來實現,(2)通過DBUtils的靜態方法
setProperty(T,fieldName,fieldValue)來實現;具體參考.bean.BeanUtileTest
public static <T>T getObject(Class<T> clazz,String sql,Object ... args )throws Exception{
T entity =null;
Connection connection=JdbcTools.getConnection();
PreparedStatement preparedStatement=(PreparedStatement) connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
preparedStatement.setObject(i+1, args[i]);
}
ResultSet resultSet=preparedStatement.executeQuery();
Map<String, Object>values=new HashMap<String, Object>();
ResultSetMetaData resultSetMetaData=resultSet.getMetaData();
while(resultSet.next()){
for(int i=0;i<resultSetMetaData.getColumnCount();i++){
String columLabel = resultSetMetaData.getColumnLabel(i+1);
Object columValue = resultSet.getObject(columLabel);
values.put(columLabel,columValue);
}
}
if(values.size()>0){
entity=clazz.newInstance();
java.lang.reflect.Field[] field=entity.getClass().getDeclaredFields();
System.out.println("for before");
for(Map.Entry<String,Object>entry : values.entrySet()){
String fieldName=entry.getKey();
Object fieldValue=entry.getValue();
//使用BeanUtils.setProperty(),功能和註釋部分一樣
BeanUtils.setProperty(entity, fieldName, fieldValue);
// for(int i=0;i<field.length;i++){
// field[i].setAccessible(true);
// try {
// if(field[i].getType().equals(String.class)){
// if(field[i].getName().equals(fieldName)){
// field[i].set(entity, fieldValue);
// }
// }else if(field[i].getType().equals(int.class)){
// if(field[i].getName().equals(fieldName)){
// field[i].set(entity, fieldValue);
// }
// }
// } catch (Exception e) {
// field[i].setAccessible(true);
// }
// }
}
}
return entity;
}
/**
* 這個方法的實現跟上面的差不多;
* 這是將結果集轉化為 List<T> 的方法
*/
public static <T> List<T> getObjects(Class<T> clazz,String sql,Object ... args)
throws Exception{
T entity=null;
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
List<Map<String, Object>>list=new ArrayList<Map<String,Object>>();
List<T>listObject=new ArrayList<T>();
try{
connection=JdbcTools.getConnection();
preparedStatement=(PreparedStatement) connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
preparedStatement.setObject(i+1, args[i]);
}
resultSet=preparedStatement.executeQuery();
ResultSetMetaData resultSetMetaData=resultSet.getMetaData();
while(resultSet.next()){
Map<String,Object>values=new HashMap<String,Object>();
for(int i=0;i<resultSetMetaData.getColumnCount();i++){
String columLable=resultSetMetaData.getColumnLabel(i+1);
Object columValue=resultSet.getObject(i+1);
values.put(columLable, columValue);
}
list.add(values);
}
}catch (Exception e) {
e.printStackTrace();
}finally{
JdbcTools.release(resultSet, preparedStatement, connection);
}
if(!list.isEmpty()){
Iterator<Map<String, Object>> iterator=list.iterator();
while(iterator.hasNext()){
entity=clazz.newInstance();
java.lang.reflect.Field[] field=entity.getClass().getDeclaredFields();
Map<String,Object>values=iterator.next();
for(Map.Entry<String,Object>entry:values.entrySet()){
String fieldName=entry.getKey();
Object fieldValue=entry.getValue();
for(int i=0;i<field.length;i++){
field[i].setAccessible(true);
if(field[i].getType().equals(String.class)){
if(field[i].getName().equals(fieldName)){
field[i].set(entity, fieldValue);
}
}else if(field[i].getType().equals(int.class)){
if(field[i].getName().equals(fieldName)){
field[i].set(entity, fieldValue);
}
}
}
}
listObject.add(entity);
}
}
return listObject;
}
----------------------------------------------------------------------------------------
4、關閉資源;
//參考:jdbc_connection.JdbcTools
public static void release(ResultSet resultSet,Statement statement,Connection connection){
if(resultSet!=null){
try {
resultSet.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(statement!=null){
try {
statement.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(connection!=null){
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
}
----------------------------------------------------------------------------------
5、批量處理:
//參考 :controller.Batch_processed
/**
*
* 批處理
* 電腦不穩定測試難
*
* @throws Exception
*/
@Test
public void testBatch() throws Exception{
Connection connection=null;
java.sql.PreparedStatement preparedStatement=null;
String sql="insert into customers values(?,?,?)";
try {
connection=JdbcTools.getConnection();
JdbcTools.beginTransaction(connection);
preparedStatement=connection.prepareStatement(sql);
long begin=System.currentTimeMillis();
for(int i=0;i<10000;i++){
//核心程式碼
preparedStatement.setInt(1, i+1);
preparedStatement.setString(2, "name_"+i);
preparedStatement.setString(3, "2016-8-6");
preparedStatement.addBatch();
if((i%300)==0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
}
if(10000%300!=0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
JdbcTools.commit(connection);
long end=System.currentTimeMillis();
System.out.println(end-begin);//5281
} catch (Exception e) {
e.printStackTrace();
JdbcTools.rollback(connection);
}finally{
JdbcTools.release(preparedStatement, connection);
}
}
--------------------------------------------------------------------------------
6、事務處理;
//參考:controller.transactionTest
/**
* 資料庫隔離事務--READ_COMMITED 和 READ_UNCOMMITED 的區別
* 測試用例
*
*
*/
@Test
public void testTransactionIsolutionUpdate(){
Connection connection = null;
try {
connection =JdbcTools.getConnection();
connection.setAutoCommit(false);
String sql="update book set price=price+100 where id=9";
update(connection, sql);
//connection.commit();先提交再讀取
//讀取未提交的資料
String sql1="select price from book where id=9";
int price =(int)getSingleColum(sql1);
System.out.println(price);
connection.commit();//先讀取再提交
} catch (Exception e) {
e.printStackTrace();
}finally{
JdbcTools.release(null,null,connction);
}
}