什么是jdbc:
使用java代码(程序)发送sql语句的技术,就是jdbc技术!!!!
jdbc是sun公司在Java的JDK中定义的一套连接数据库的规范(接口),接口的实现由各个数据库厂商去实现(驱动包),
接口的具体内容请参考JDK中的java.sql.*以及Javax.sql.*里面的内容
JDBC各个数据库的URL
JDBC的URL=协议名+子协议名+数据源名。
a 协议名总是“jdbc”。
b 子协议名由JDBC驱动程序的编写者决定。
c 数据源名也可能包含用户与口令等信息;这些信息也可单独提供。
几种常见的数据库连接
-------------------------------oracle------------------
驱动:oracle.jdbc.driver.OracleDriver
URL:jdbc:oracle:thin:@machine_name:port:dbname
注:machine_name:数据库所在的机器的名称;
port:端口号,默认是1521
-------------------------------mysql-------------------
驱动:com.mysql.jdbc.Driver
URL:jdbc:mysql://machine_name:port/dbname
注:machine_name:数据库所在的机器的名称;
port:端口号,默认3306
---------------------------SQL Server------------------
驱动:com.microsoft.jdbc.sqlserver.SQLServerDriver
URL:jdbc:microsoft:sqlserver://<machine_name><:port>;DatabaseName=<dbname>
注:machine_name:数据库所在的机器的名称;
port:端口号,默认是1433
--------------------------DB2--------------------------
驱动:com.ibm.db2.jdbc.app.DB2Driver
URL:jdbc:db2://<machine_name><:port>/dbname
注:machine_name:数据库所在的机器的名称;
port:端口号,默认是5000
-------------------------------------------------------
jdbc连接数据库的几种连接方式
package cn.itcast.com.day01;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;
/**
* jdbc连接数据库的方法
* @author CHT
*
*/
public class test1 {
private String url="jdbc:mysql://127.0.0.1:3306/loveoffice";
private String user="root";
private String password="admin";
/**
* 第一种方法
* 驱动程序类连接数据库
*/
@Test
public void test1(){
try {
//1.创建驱动类对象
/**
* Driver在jdk中的java.sql包下,由sun公司设计的连接数据库的接口
* Driver为sun公司提供的连接数据库的接口(jdbc规范),com.mysql.jdbc.Driver()为mysql驱动包里面实现的Driver接口具体的连接数据库的实现
* 其中org.gjt.mm.mysql.Driver()为老版本,由gjt组织开发,为兼顾老版本,固这两个方式实现数据库的连接都可以
*
* Driver更多介绍详见jdk(java.sql.Driver类)
*
*/
Driver driver=new com.mysql.jdbc.Driver();
// Driver driver=new org.gjt.mm.mysql.Driver();
//设置用户名和密码
Properties properties=new Properties();
properties.setProperty("user", user);//key值固定位user
properties.setProperty("password", password);//key值固定位password
//2.连接数据库
Connection connection=driver.connect(url, properties);
System.out.println("connection="+connection);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 第二种方法
* 使用驱动管理器类连接数据库
*
* 驱动管理器类可以管理多组驱动程序类,如:mysql、oracle等,驱动管理器类再根据获取连接对象时候的url来判断是具体连接oracle还是mysql,进而调用对应的驱动类
*/
@Test
public void test2(){
try {
Driver driver = new com.mysql.jdbc.Driver();
// Driver driver2= new com.oracle.jdbc.Driver();
DriverManager.registerDriver(driver);
Connection connection=DriverManager.getConnection(url, user, password);
System.out.println(connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 第三种方法
* 使用驱动管理器类连接数据库
*
* 查看com.mysql.jdbc.Driver()实现类中的源码得知,com.mysql.jdbc.Driver()中有一段静态代码块,如下:
* static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
由此得知,Driver的实现类在创建对象的时候就将自己注册到驱动管理器类中了,因此可以直接创建驱动程序类就自动帮我们将驱动类注册到了驱动管理器类中,
因此可以直接调用驱动管理器类直接获取连接对象Connection,所以方法二中,driver被注册了两次
*/
@Test
public void test3(){
try {
Driver driver = new com.mysql.jdbc.Driver();
// Driver driver2= new com.oracle.jdbc.Driver();
// DriverManager.registerDriver(driver);
Connection connection=DriverManager.getConnection(url, user, password);
System.out.println(connection+"----3");
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 第四种方法(推荐连接方式)
* 使用类加载,直接将驱动类注册到驱动管理器类中
*
* 使用类加载时,因执行了静态代码块,所以可以无需创建驱动程序对相关就可以直接通过类加载来调用静态代码块将驱动程序类注册到驱动管理器中
* 直接从驱动管理器中获取连接对象连接数据库即可
*/
@Test
public void test4(){
try {
//通过得到字节码对象的方式加载静态代码块,从而注册驱动程序
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection(url, user, password);
System.out.println("connection="+connection+"-----4");
} catch (Exception e) {
e.printStackTrace();
}
}
}
jdbc接口核心API
Driver接口:表示Java驱动程序接口。所有的具体的数据库厂商都要来实现此接口。
connect(url,properties):连接数据库的方法。
DriverManager类:驱动管理器类,用户管理所有注册的驱动程序
registerDriver(driver):注册驱动类对象
Connection getConnection(url,user,passwor);获取连接对象
Connection接口:表示Java程序和数据库的连接对象
StatementcreateStatement();创建Statement对象
PreparedStatementpreparedStatement(String sql);创建preparedStatement对象
CallableStatementprepareCall(String sql) 创建CallabelStatement对象
Statement接口:用于执行静态的sql语句
int executeUpdate(String sql);指向静态的更新sql语句(DDL、DML)
ResultSet executeQuery(String sql)
PreparedStatement接口:用于执行预编译sql语句
int executeUpdate():执行预编译的更新sql语句(DDL,DML)
ResultSet executeQuery() :执行预编译的查询sql语句(DQL)
CallableStatement接口:用于执行存储过程的sql语句(call xxx)
ResultSet executeQuery() :调用存储过程的方法
ResultSet接口:用于封装查询出来的数据
boolean next() :将光标移动到下一行
getXX() :获取列的值
使用Statement执行sql语句
执行DDL语句
/**
* 执行DDL语句(创建表)
*/
@Test
public void test1(){
Statement stmt = null;
Connection conn = null;
try {
//1.驱动注册程序
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
conn = DriverManager.getConnection(url, user, password);
//3.创建Statement
stmt = conn.createStatement();
//4.准备sql
String sql = "CREATE TABLE student(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),gender VARCHAR(2))";
//5.发送sql语句,执行sql语句,得到返回结果
int count = stmt.executeUpdate(sql);
//6.输出
System.out.println("影响了"+count+"行!");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally{
//7.关闭连接(顺序:后打开的先关闭)
if(stmt!=null)
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
执行DML语句
/**
* 使用Statement执行DML语句
* @author APPle
*
*/
public class Demo2 {
private String url = "jdbc:mysql://localhost:3306/day17";
private String user = "root";
private String password = "root";
/**
* 增加
*/
@Test
public void testInsert(){
Connection conn = null;
Statement stmt = null;
try {
//通过工具类获取连接对象
conn = JdbcUtil.getConnection();
//3.创建Statement对象
stmt = conn.createStatement();
//4.sql语句
String sql = "INSERT INTO student(NAME,gender) VALUES('李四','女')";
//5.执行sql
int count = stmt.executeUpdate(sql);
System.out.println("影响了"+count+"行");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally{
//关闭资源
/*if(stmt!=null)
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}*/
JdbcUtil.close(conn, stmt);
}
}
/**
* 修改
*/
@Test
public void testUpdate(){
Connection conn = null;
Statement stmt = null;
//模拟用户输入
String name = "陈六";
int id = 3;
try {
/*//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
conn = DriverManager.getConnection(url, user, password);*/
//通过工具类获取连接对象
conn = JdbcUtil.getConnection();
//3.创建Statement对象
stmt = conn.createStatement();
//4.sql语句
String sql = "UPDATE student SET NAME='"+name+"' WHERE id="+id+"";
System.out.println(sql);
//5.执行sql
int count = stmt.executeUpdate(sql);
System.out.println("影响了"+count+"行");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally{
//关闭资源
/*if(stmt!=null)
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}*/
JdbcUtil.close(conn, stmt);
}
}
/**
* 删除
*/
@Test
public void testDelete(){
Connection conn = null;
Statement stmt = null;
//模拟用户输入
int id = 3;
try {
/*//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
conn = DriverManager.getConnection(url, user, password);*/
//通过工具类获取连接对象
conn = JdbcUtil.getConnection();
//3.创建Statement对象
stmt = conn.createStatement();
//4.sql语句
String sql = "DELETE FROM student WHERE id="+id+"";
System.out.println(sql);
//5.执行sql
int count = stmt.executeUpdate(sql);
System.out.println("影响了"+count+"行");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally{
//关闭资源
/*if(stmt!=null)
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}*/
JdbcUtil.close(conn, stmt);
}
}
}
执行DQL语句
/**
* 使用Statement执行DQL语句(查询操作)
* @author APPle
*/
public class Demo3 {
@Test
public void test1(){
Connection conn = null;
Statement stmt = null;
try{
//获取连接
conn = JdbcUtil.getConnection();
//创建Statement
stmt = conn.createStatement();
//准备sql
String sql = "SELECT * FROM student";
//执行sql
ResultSet rs = stmt.executeQuery(sql);
//移动光标
/*boolean flag = rs.next();
flag = rs.next();
flag = rs.next();
if(flag){
//取出列值
//索引
int id = rs.getInt(1);
String name = rs.getString(2);
String gender = rs.getString(3);
System.out.println(id+","+name+","+gender);
//列名称
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
System.out.println(id+","+name+","+gender);
}*/
//遍历结果
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
System.out.println(id+","+name+","+gender);
}
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}finally{
JdbcUtil.close(conn, stmt);
}
}
}
使用PreparedStatement执行sql语句
public class Demo1 {
/**
* 增加
*/
@Test
public void testInsert() {
Connection conn = null;
PreparedStatement stmt = null;
try {
//1.获取连接
conn = JdbcUtil.getConnection();
//2.准备预编译的sql
String sql = "INSERT INTO student(NAME,gender) VALUES(?,?)"; //?表示一个参数的占位符
//3.执行预编译sql语句(检查语法)
stmt = conn.prepareStatement(sql);
//4.设置参数值
/**
* 参数一: 参数位置 从1开始
*/
stmt.setString(1, "李四");
stmt.setString(2, "男");
//5.发送参数,执行sql
int count = stmt.executeUpdate();
System.out.println("影响了"+count+"行");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt);
}
}
/**
* 修改
*/
@Test
public void testUpdate() {
Connection conn = null;
PreparedStatement stmt = null;
try {
//1.获取连接
conn = JdbcUtil.getConnection();
//2.准备预编译的sql
String sql = "UPDATE student SET NAME=? WHERE id=?"; //?表示一个参数的占位符
//3.执行预编译sql语句(检查语法)
stmt = conn.prepareStatement(sql);
//4.设置参数值
/**
* 参数一: 参数位置 从1开始
*/
stmt.setString(1, "王五");
stmt.setInt(2, 9);
//5.发送参数,执行sql
int count = stmt.executeUpdate();
System.out.println("影响了"+count+"行");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt);
}
}
/**
* 删除
*/
@Test
public void testDelete() {
Connection conn = null;
PreparedStatement stmt = null;
try {
//1.获取连接
conn = JdbcUtil.getConnection();
//2.准备预编译的sql
String sql = "DELETE FROM student WHERE id=?"; //?表示一个参数的占位符
//3.执行预编译sql语句(检查语法)
stmt = conn.prepareStatement(sql);
//4.设置参数值
/**
* 参数一: 参数位置 从1开始
*/
stmt.setInt(1, 9);
//5.发送参数,执行sql
int count = stmt.executeUpdate();
System.out.println("影响了"+count+"行");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt);
}
}
/**
* 查询
*/
@Test
public void testQuery() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
//1.获取连接
conn = JdbcUtil.getConnection();
//2.准备预编译的sql
String sql = "SELECT * FROM student";
//3.预编译
stmt = conn.prepareStatement(sql);
//4.执行sql
rs = stmt.executeQuery();
//5.遍历rs
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
System.out.println(id+","+name+","+gender);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
//关闭资源
JdbcUtil.close(conn,stmt,rs);
}
}
}
preparedStatement预编译原理图
PreparedStatement vs Statment
1)语法不同:PreparedStatement可以使用预编译的sql,而Statment只能使用静态的sql
2)效率不同: PreparedStatement可以使用sql缓存区,效率比Statment高
3)安全性不同: PreparedStatement可以有效防止sql注入,而Statment不能防止sql注入。
推荐使用PreparedStatement
CallableStatement执行存储过程
/**
* 使用CablleStatement调用存储过程
* @author APPle
*
*/
public class Demo1 {
/**
* 调用带有输入参数的存储过程
* CALL pro_findById(4);
*/
@Test
public void test1(){
Connection conn = null;
CallableStatement stmt = null;
ResultSet rs = null;
try {
//获取连接
conn = JdbcUtil.getConnection();
//准备sql
String sql = "CALL pro_findById(?)"; //可以执行预编译的sql
//预编译
stmt = conn.prepareCall(sql);
//设置输入参数
stmt.setInt(1, 6);
//发送参数
rs = stmt.executeQuery(); //注意: 所有调用存储过程的sql语句都是使用executeQuery方法执行!!!
//遍历结果
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
System.out.println(id+","+name+","+gender);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt ,rs);
}
}
/**
* 执行带有输出参数的存储过程
* CALL pro_findById2(5,@NAME);
*/
@Test
public void test2(){
Connection conn = null;
CallableStatement stmt = null;
ResultSet rs = null;
try {
//获取连接
conn = JdbcUtil.getConnection();
//准备sql
String sql = "CALL pro_findById2(?,?)"; //第一个?是输入参数,第二个?是输出参数
//预编译
stmt = conn.prepareCall(sql);
//设置输入参数
stmt.setInt(1, 6);
//设置输出参数(注册输出参数)
/**
* 参数一: 参数位置
* 参数二: 存储过程中的输出参数的jdbc类型 VARCHAR(20)
*/
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
//发送参数,执行
stmt.executeQuery(); //结果不是返回到结果集中,而是返回到输出参数中
//得到输出参数的值
/**
* 索引值: 预编译sql中的输出参数的位置
*/
String result = stmt.getString(2); //getXX方法专门用于获取存储过程中的输出参数
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt ,rs);
}
}
}