工具類JdbuUtils
用于獲取連接已經關閉相關資源
package JDBCutils; import java.io.InputStream; import java.sql.DriverManager; import java.util.Properties; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @author ztr * @version 創建時間:2021年3月29日 上午10:20:16 類說明 */ /* * 獲取連接 * @return Connection * */ public class JdbcUtils { public JdbcUtils() { super(); // TODO Auto-generated constructor stub } public static Connection getConnection() throws Exception { // 讀取組態檔的基本資訊 // 獲取連接 InputStream is = ClassLoader.getSystemClassLoader() .getResourceAsStream("jdbc.properties"); Properties properties = new Properties(); properties.load(is); String user = properties.getProperty("user"); String password = properties.getProperty("password"); String url = properties.getProperty("url"); String driverClass = properties.getProperty("driverClass"); // 加載驅動 Class.forName(driverClass); Connection connection = DriverManager .getConnection(url, user, password); return connection; }
/*
* 關閉資源
* */
public static void closeResource(Connection connection,PreparedStatement ps){
try {
if (ps != null)
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} /* * 關閉資源 * */ public static void closeResource1(Connection connection,PreparedStatement ps,ResultSet rs){ try { if (ps != null) ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (connection != null) connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (rs != null) rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
組態檔jdbc.properties
user=root
password=xxx//換成所連接資料庫的密碼
url=jdbc:mysql://localhost:3306/school//school是所連接的database
driverClass=com.mysql.cj.jdbc.Driver
向資料庫中添加資料
@Test public void testinsertinfo() { // 讀取組態檔的基本資訊 // 獲取連接 Connection connection = null; PreparedStatement prepareStatement = null; try { // 讀取組態檔的基本資訊 // 獲取連接 InputStream is = ClassLoader.getSystemClassLoader() .getResourceAsStream("jdbc.properties"); Properties properties = new Properties(); properties.load(is); String user = properties.getProperty("user"); String password = properties.getProperty("password"); String url = properties.getProperty("url"); String driverClass = properties.getProperty("driverClass"); // 加載驅動 Class.forName(driverClass); connection = DriverManager.getConnection(url, user, password); // 預編譯sql陳述句,回傳prepareStatement實體 // ?占位符 String sql = "insert into student(sname,gender,class_id)values(?,?,?)"; prepareStatement = connection.prepareStatement(sql); // 填充占位符
//需要注意的是setString()方法的下標是從1開始
prepareStatement.setString(1, "哪炸"); prepareStatement.setString(2, "男"); prepareStatement.setInt(3, 3); // 執行sql prepareStatement.execute(); // 資源的關閉 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (prepareStatement != null) prepareStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (connection != null) connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
修改資料庫資料
@Test public void updatedate() { // 獲取連接 Connection connection = null; PreparedStatement prepareStatement = null; try { connection = JdbcUtils.getConnection(); // 預編譯sql陳述句,回傳preparesStatement String sql = "update student set sname = ? where sid = ? "; prepareStatement = connection.prepareStatement(sql); // 填充占位符 prepareStatement.setString(1, "宋江"); prepareStatement.setInt(2, 1); // 執行 prepareStatement.execute(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 資源的關閉 JdbcUtils.closeResource(connection, prepareStatement); } // 資源的關閉 JdbcUtils.closeResource(connection, prepareStatement); }
洗掉資料庫資料
// 洗掉資料庫資料 @Test public void droptest() { // 獲取連接 Connection connection = null; PreparedStatement prepareStatement = null; try { connection = JdbcUtils.getConnection(); // 預編譯sql陳述句,回傳preparesStatement String sql = "delete from student where sid = ? "; prepareStatement = connection.prepareStatement(sql); // 填充占位符 prepareStatement.setObject(1, 4); // 執行 prepareStatement.execute(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 資源的關閉 JdbcUtils.closeResource(connection, prepareStatement); } // 資源的關閉 JdbcUtils.closeResource(connection, prepareStatement); }
至此我們發現增刪改操大部分都相同這時我們可以寫一個對增刪改操作都通用的方法,是代碼更具有有復合性,
我們可以發現增刪改操作其實差異就在sql陳述句中,我們不但要考慮sql還要考慮sql陳述句中需要我們去填充多少個占位符,這時我們可以通過傳入可變引數來解決這個問題,
增刪改的通用操作
// 通用的增刪改操作 public void update(String sql, Object... args) { // 獲取資料連接 Connection connection = null; // 預編譯sql陳述句回傳preparedStatement PreparedStatement prepareStatement = null; try { connection = JdbcUtils.getConnection(); prepareStatement = connection.prepareStatement(sql); // 填充占位符 // prepareStatement.setObject的下標從1開始 for (int i = 0; i < args.length; i++) { prepareStatement.setObject(i + 1, args[i]); } // 執行 prepareStatement.execute(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 資源的關閉 JdbcUtils.closeResource(connection, prepareStatement); } }
@Test
public void testcommonupdate() {
String sql = "delete from student where sid = ?";
update(sql, 1);
}
查詢操作和增刪改操作不同的是,查詢需要回傳查詢的結果,對所查詢到的資料進行處理并且顯示出來
@Test public void QueryTest() { Connection connection = null; PreparedStatement prepareStatement = null; // 執行回傳結果集 ResultSet resultSet = null; try { connection = JdbcUtils.getConnection(); String sql = "select * from student where sid = 2"; prepareStatement = connection.prepareStatement(sql); resultSet = prepareStatement.executeQuery(); // 處理結果集 if (resultSet.next()) {// 判斷結果集下一條是否有資料,若有則指標下移,若回傳為false則指標不下移 int id = resultSet.getInt(1); String sname = resultSet.getString(2); String gender = resultSet.getString(3); int class_id = resultSet.getInt(4); // //方式一 // System.out.println("id "+id+"sname="+sname+"gender="+gender+"calss_id"+class_id); // //方式二 // Object[] objects = new Object[]{id,sname,gender,class_id}; // //方式三,將資料封裝成一個物件 Student student = new Student(id, sname, gender, class_id); System.out.println(student); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 關閉資源 JdbcUtils.closeResource1(connection, prepareStatement, resultSet); } }
這個方發大家可以很容易的發現它的局限性,只能實作對一個表的固定查詢操作,如果我們需要的欄位不同時,則此方法就失去了意義,
迭代--我們可以通過反射動態的獲取sql陳述句的查詢的列數以及對應的列名,
查詢的迭代代碼
public static Student quaryStudent(String sql, Object... args) {
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet resultSet = null;
try {
connection = JdbcUtils.getConnection();
prepareStatement = connection.prepareStatement(sql);
// 填充占位符
for (int i = 0; i < args.length; i++) {
prepareStatement.setObject(i + 1, args[i]);
}
resultSet = prepareStatement.executeQuery();
// 獲取結果即的元資料metaData
ResultSetMetaData metaData = https://www.cnblogs.com/zoutingrong/p/resultSet.getMetaData();
// 通過metaData獲取結果集中的列數
int count = metaData.getColumnCount();
if (resultSet.next()) {
Student student = new Student();
// 處理一行資料中的每一個列
for (int i = 0; i < count; i++) {
Object colunmValue = https://www.cnblogs.com/zoutingrong/p/resultSet.getObject(i + 1);
// 獲取每個列的列名
// String columnName = metaData.getColumnName(i + 1);
/*
* 使用getClumnlabel代替getColumnName
* 因為可能鎖對應的類的屬性和資料表的列名不一致
* 需要注意的是此時sql需要為列名取別名
* eg:select sid 類對應的屬性名 from where sid =?
* getClumnLabel當為列名取別名時其回傳的是別名,沒有別名時回傳的是列名
* */
String columnName = metaData.getColumnLabel(i + 1);
// 給student物件指定的columName屬性,賦值為columValue,通過反射
Field field = Student.class.getDeclaredField(columnName);
// 考慮其屬性為私有屬性
field.setAccessible(true);
field.set(student, colunmValue);
}
return student;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 進行資源的關閉
JdbcUtils.closeResource1(connection, prepareStatement, resultSet);
}
return null;
}
@Test
public void qurytest2() {
String sql = "select * from student";
Student student = PreparedStamentTest.quaryStudent(sql);
System.out.println(student);
}
可能大家會對元資料有疑惑,元資料就是修飾資料的資料,
接受資料類-Student
package bean; /** * @author ztr * @version 創建時間:2021年3月30日 下午3:22:09 * 類說明 */ public class Student { private int sid; private String sname; private String gender; private int class_id; public Student() { super(); // TODO Auto-generated constructor stub } public Student(int sid, String sname, String gender, int class_id) { super(); this.sid = sid; this.sname = sname; this.gender = gender; this.class_id = class_id; } public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getClass_id() { return class_id; } public void setClass_id(int class_id) { this.class_id = class_id; } @Override public String toString() { return "Student [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", class_id=" + class_id + "]"; } }
圖解查詢流程

迭代2:實作對全部表格的通用查詢
package preparedStament; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import org.junit.Test; import JDBCutils.JdbcUtils; import bean.Student; /** * @author ztr * @version 創建時間:2021年3月31日 下午5:10:19 * 類說明:針對不同表的通用查詢操作 */ public class QueryCommon { public <T> T GetInstance(Class<T> clazz,String sql,Object ...args){ Connection connection = null; PreparedStatement prepareStatement = null; // 獲取結果集 ResultSet resultSet = null; try { connection = JdbcUtils.getConnection(); prepareStatement = connection.prepareStatement(sql); for (int i = 0; i < args.length; i++) { prepareStatement.setObject(i + 1, args[i]); } resultSet = prepareStatement.executeQuery(); // 獲取元資料 ResultSetMetaData metaData =https://www.cnblogs.com/zoutingrong/p/ resultSet.getMetaData(); // 通過metaData獲取結果集中的列數 int columnCount = metaData.getColumnCount(); if (resultSet.next()) { T newInstance = clazz.newInstance(); for (int i = 0; i < columnCount; i++) { //獲取列值 Object columnValue = https://www.cnblogs.com/zoutingrong/p/resultSet.getObject(i + 1); // 獲取每列的列名 String columnName = metaData.getColumnName(i + 1); // 利用反射 Field field = clazz.getDeclaredField(columnName); // 考慮該屬性是否為私有 field.setAccessible(true); field.set(newInstance, columnValue); } return newInstance; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 關閉資源 JdbcUtils.closeResource1(connection, prepareStatement, resultSet); } return null; } @Test public void test(){ String sql = "select sid,sname from student where sid=?"; Student getInstance = GetInstance(Student.class, sql, 9); System.out.println(getInstance); } }
以上的查詢方法都只適用與查詢一條資料
迭代2:查詢多條資料
/** * * @param clazz * @param sql * @param args * @return List<T> */ public <T> List<T> getList(Class<T> clazz, String sql, Object... args) { Connection connection = null; PreparedStatement prepareStatement = null; // 獲取結果集 ResultSet resultSet = null; try { connection = JdbcUtils.getConnection(); prepareStatement = connection.prepareStatement(sql); for (int i = 0; i < args.length; i++) { prepareStatement.setObject(i + 1, args[i]); } resultSet = prepareStatement.executeQuery(); // 獲取元資料 ResultSetMetaData metaData =https://www.cnblogs.com/zoutingrong/p/ resultSet.getMetaData(); // 通過metaData獲取結果集中的列數 int columnCount = metaData.getColumnCount(); // 創建集合物件 ArrayList<T> list = new ArrayList<T>(); while (resultSet.next()) { T newInstance = clazz.newInstance(); for (int i = 0; i < columnCount; i++) { // 獲取列值 Object columnValue = https://www.cnblogs.com/zoutingrong/p/resultSet.getObject(i + 1); // 獲取每列的列名 String columnName = metaData.getColumnName(i + 1); // 利用反射 Field field = clazz.getDeclaredField(columnName); // 考慮該屬性是否為私有 field.setAccessible(true); field.set(newInstance, columnValue); } list.add(newInstance); } return list; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 關閉資源 JdbcUtils.closeResource1(connection, prepareStatement, resultSet); } return null; } @Test public void test1(){ String sql = "select sid,sname from student where sid < ?"; List<Student> list = getList(Student.class, sql, 10); list.forEach(System.out::println); }
運行截圖

至此,JDBC對資料庫的CURD就全部完成,此博文只是對自己學習得到階段性總結,若有錯誤之處,請諒解!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/270602.html
標籤:Java
上一篇:java
下一篇:Spring 事務介紹
