是什么?
1、理解
1、就是帮助我们连接和管理数据库
怎么用?
1、步骤
1、注册驱动
2、获取连接
3、编写sql语句
4、关闭数据库
2、简单的例子
1、例子1 (普通连接)
package com.qtedu.jdbc;
import com.mysql.jdbc.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 这是第一个jdbc程序,完成简单的操作
*/
public class Jdbc01 {
public static void main(String[] args) throws SQLException {
// 前置工作,安装connector驱动
//1.注册驱动
Driver driver = new Driver();
//2.得到连接
String url = "jdbc:mysql://localhost:3306/qt_db02";
Properties properties = new Properties();
properties.setProperty("user","root");//用户
properties.setProperty("password","123456") ;
Connection connect = driver.connect(url,properties);
// 3.执行sql语句
String sql = "insert into actor values(null,'缺氧','0', '1970-10-10' ,'110')";
//发送sql语句执行
Statement statement = connect.createStatement();
int rowupdate = statement.executeUpdate(sql);//如果是dml语句rowupdate是返回的函数
System.out.println(rowupdate> 0? "成功":"失败");
// 4.关闭资源连接
statement.close();
connect.close();
}
}
2、例子2用反射
//方法二 动态加载,更加灵活
@Test
public void connect02() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
Class aclass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aclass.newInstance();
String url = "jdbc:mysql://localhost:3306/qt_db02";
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
Connection connection = driver.connect(url,properties);
System.out.println("方式二:"+connection);
}
3、方法3使用DriverManager 替代 Driver 进行统一管理
public void connect03() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
//反射加载Driver
Class aclass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aclass.newInstance();
//创建url 和user 和password
String url = "jdbc:mysql://localhost:3306/qt_db02";
String user = "root";
String password = "123456";
DriverManager.registerDriver(driver);//注册驱动
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println("第三种连接方式"+connection);
}
4、使用Class.forName 自动完成注册驱动,简化代码
public void connect04() throws ClassNotFoundException, SQLException {
//加载Driver 类时,会自动完成驱动注册(Driver底层代码中有一个static代码块编写了DriverManager.registerDriver( new driver);方法
Class aclass = Class.forName("com.mysql.jdbc.Driver");
//创建url和user和password
String url = "jdbc:mysql://localhost:3306/qt_db02";
String user = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println("第四种连接方式"+connection);
}