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