赞
踩
目录
JDBC的本质
JDBC操作MySQL数据库
01
02
03
- package JDBC;
-
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.Statement;
-
- public class JDBCDemo {
- public static void main(String[] args) throws Exception {
- //1.注册驱动
- Class.forName("com.mysql.jdbc.Driver");
- //2.获取连接
- String url = "jdbc:mysql://127.0.0.1:3306/db01";
- String username = "root";
- String password = "123456";
- Connection conn = DriverManager.getConnection(url,username,password);
- //3.定义sql
- String sql = "update user set password = 666666 where id = 1";
- //4.获取执行sql的对象Statement
- Statement stmt = conn.createStatement();
- //5.执行sql
- int count = stmt.executeUpdate(sql);
- //6.处理结果
- System.out.println(count);
- //7.释放资源
- stmt.close();
- conn.close();
- }
- }
关于//1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); 为什么可以注册驱动成功?
我们找到如下内容就会发现我们下载的jar包中已经注册了
- // Driver 接口,所有数据库厂商必须实现的接口,表示这是一个驱动类。
- public class Driver extends com.mysql.cj.jdbc.Driver {
- public Driver() throws SQLException {
- }
-
- static {
- System.err.println("Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.");
- }
- }
从 JDBC3 开始,可以不用注册驱动而直接使用。Class.forName("com.mysql.jdbc.Driver"); 这句话可以省略。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。