1.JDBC爲何會存在?java
2.JDBC的實現基於這樣的思想:根據JDBC編寫的程序可以與一個驅動管理器通訊,驅動管理器經過驅動程序與實際的數據庫進行通訊。mysql
3.如何使用JDBC與數據庫鏈接?spring
使用mysql做爲例子:(mysql-connection-java jar)sql
4.代碼演示:數據庫
使用jdbc查詢id=1的name值網絡
import java.sql.*; public class JDBCTest1 { public static void jdbctest(){ try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/datatest?" + "useEncoding=true&characterEncoding=utf-8&serverTimezone=UTC","root","123456"); //這裏的鏈接符號是&,而在spring的配置文件中使用的是& String sql="select * from student where id=?"; PreparedStatement preparedStatement=connection.prepareStatement(sql); preparedStatement.setInt(1,1); ResultSet resultSet= preparedStatement.executeQuery(); while(resultSet.next()){ System.out.println(resultSet.getString("name")); } resultSet.close(); preparedStatement.close();// 別忘記釋放資源 connection.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) { JDBCTest1.jdbctest(); } }
5.數據庫鏈接池spa
有了鏈接池以後,Dao層會去鏈接池中得到已經建立好的鏈接,不用再去新建鏈接,而後同數據庫進行通信。code
public class C3P0Test { public static void testC3p0() throws PropertyVetoException, SQLException { //建立鏈接池對象 ComboPooledDataSource comboPooledDataSource=new ComboPooledDataSource(); //設置數據源 comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver"); comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/datatest?useEncoding=true&characterEncoding=utf-8&serverTimezone=UTC"); comboPooledDataSource.setUser("root"); comboPooledDataSource.setPassword("123456"); //獲取鏈接 Connection connection=comboPooledDataSource.getConnection(); //sql語句 String sql="update student set name=? where id=?"; PreparedStatement ps=connection.prepareStatement(sql); ps.setString(1,"liuchen"); ps.setInt(2,1); if(ps.executeUpdate()>0){ System.out.println("修改爲功!"); } } public static void main(String[] args) throws PropertyVetoException, SQLException { C3P0Test.testC3p0(); } }
修改爲功!server