jdbc的工具類:
要使用JDBC來操作數(shù)據(jù)庫
API:java.sql包中的接口與類
JDBC:用來來接數(shù)據(jù)庫并對數(shù)據(jù)操作的一種技術(shù)
Mysql的驅(qū)動程序:mysql-connector-java-5.1.38.jar
需要從https://mvnrepository.com下載驅(qū)動下載完成后需要引用到項(xiàng)目中
jdbc的操作流程:
1.加載驅(qū)動
2.獲取連接Connection
3.獲取到Statement對象用于執(zhí)行靜態(tài)的SQL語句
4.執(zhí)行查詢返回一個(gè)結(jié)果集ResultSet并對結(jié)果集遍歷以對象的方式保存到集合中
-
5.關(guān)閉資源 ResultSet Statement Connection
public class DBUtils {public static void main(String[] args) {
*1.加載驅(qū)動程序
try {- Class.forName("com.mysql.jdbc.Driver");
*2.獲取連接
*Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/demo06_db?useUnicode=true&characterEncoding=utf8&autoReconnect=true","root","LZB25800");
*3.獲取到Statement對象:用于向數(shù)據(jù)庫發(fā)送sql語句,執(zhí)行DML(insert update delete)或select
- Class.forName("com.mysql.jdbc.Driver");
Statement statement=connection.createStatement();int isRigth= statement.executeUpdate("insert into admin(username,password) values('fun','22222')");int isRigth1=statement.executeUpdate(" delete from admin where id=1");System.out.println(isRigth1); ResultSet rs=statement.executeQuery("select * from admin");-
List<Admin> list=new ArrayList<>(); while(rs.next()){ int id=rs.getInt("id");//獲取某一行的第一列 String username=rs.getString("username");//獲取某一行的第二列 String password=rs.getString("password");//獲取某一行的第三列 *將數(shù)據(jù)封裝到Admin中 Admin admin=new Admin(); admin.setId(id); admin.setUsername(username); admin.setPossword(password); *將對象保存到集合中 list.add(admin); System.out.println(id+"--"+username+"--"+password); }*4.關(guān)閉資源
- rs.close();
- statement.close();
- connection.close();
} catch (ClassNotFoundException e) { - TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) { - TODO Auto-generated catch block
e.printStackTrace();
}
}
}
JDBC的優(yōu)點(diǎn):
直接底層操作,提供了很簡單、便捷的訪問數(shù)據(jù)庫的方法,跨平臺
性比較強(qiáng)。靈活性比較強(qiáng),可以寫很復(fù)雜的SQL語句。
JDBC的缺點(diǎn):
因?yàn)镴AVA是面向?qū)ο蟮?,JDBC沒有做到使數(shù)據(jù)能夠面向?qū)ο蟮木幊蹋钩绦騿T的思考仍停留在SQL語句上。
操作比較繁瑣,很多代碼需要重復(fù)寫很多次。
如果遇到批量操作,頻繁與數(shù)據(jù)庫進(jìn)行交互,容易造成效率的下降。