jdbc入门
之前操作数据
1)通过mysql的client工具,登录数据库server (mysql -u root -p 密码)
2)编写sql语句
3)发送sql语句到数据库server运行
什么是jdbc?
使用java代码(程序)发送sql语句的技术,就是jdbc技术。!
!
。
使用jdbc发送sql前提
登录数据库server(连接数据库server)
数据库的IP地址
端口
数据库username
密码
package gz.itcast.a_jdbc;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Properties;
import org.junit.Test;
/**
* jdbc连接数据库
* @author APPle
*
*/
public class Demo1 {
//连接数据库的URL
private String url = "jdbc:mysql://localhost:3306/day17";
// jdbc协议:数据库子协议:主机:端口/连接的数据库 //
private String user = "root";//username
private String password = "root";//密码
/**
* 第一种方法
* @throws Exception
*/
@Test
public void test1() throws Exception{
//1.创建驱动程序类对象
Driver driver = new com.mysql.jdbc.Driver(); //新版本号
//Driver driver = new org.gjt.mm.mysql.Driver(); //旧版本号
//设置username与password
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
//2.连接数据库,返回连接对象
Connection conn = driver.connect(url, props);
System.out.println(conn);
}
/**
* 另外一种方法
* 使用驱动管理器类连接数据库(注冊了两次。不是必需。为什么注冊了两次。请看Driver类的源码)
* @throws Exception
*/
@Test
public void test2() throws Exception{
Driver driver = new com.mysql.jdbc.Driver();
//Driver driver2 = new com.oracle.jdbc.Driver();
//1.注冊驱动程序(能够注冊多个驱动程序)
DriverManager.registerDriver(driver);
//DriverManager.registerDriver(driver2);
//2.连接到详细的数据库
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
/**
* (推荐使用这样的方式连接数据库)
* 推荐使用载入驱动程序类 来 注冊驱动程序
* @throws Exception
*/
@Test
public void test3() throws Exception{
//1.通过得到字节码对象的方式载入静态代码块。从而注冊驱动程序
Class.forName("com.mysql.jdbc.Driver");
//2.连接到详细的数据库
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
}
Driver源码:
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
static {
try {
java.sql.DriverManager.registerDriver(new Driver()); //此处直接注冊一个驱动
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
}
}
JDBC接口核心的API
java.sql.* 和 javax.sql.* |- Driver接口: 表示java驱动程序接口。全部的详细的数据库厂商要来实现此接口。
|- connect(url, properties): 连接数据库的方法。
url: 连接数据库的URL URL语法: jdbc协议:数据库子协议://主机:端口/数据库 user: 数据库的username password: 数据库用户密码 |- DriverManager类: 驱动管理器类,用于管理全部注冊的驱动程序 |-registerDriver(driver) : 注冊驱动类对象 |-Connection getConnection(url,user,password); 获取连接对象 |- Connection接口: 表示java程序和数据库的连接对象。 |- Statement createStatement() : 创建Statement对象 |- PreparedStatement prepareStatement(String sql) 创建PreparedStatement对象 |- CallableStatement prepareCall(String sql) 创建CallableStatement对象 |- Statement接口: 用于运行静态的sql语句 |- int executeUpdate(String sql) : 运行静态的更新sql语句(DDL,DML) |- ResultSet executeQuery(String sql) :运行的静态的查询sql语句(DQL) 子接口: |-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与Statment差别
1)语法不同:PreparedStatement能够使用预编译的sql,而Statment仅仅能使用静态的sql
2)效率不同: PreparedStatement能够使用sql缓存区,效率比Statment高
3)安全性不同: PreparedStatement能够有效防止sql注入,而Statment不能防止sql注入。
用户登录模拟sql注入风险
package gz.itcast.c_prepared;
import gz.itcast.util.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
/**
* 模拟用户登录效果
* @author APPle
*
*/
public class Demo2 {
//模拟用户输入
//private String name = "ericdfdfdfddfd' OR 1=1 -- "; //这样无论如何都会登陆成功
private String name = "eric";
//private String password = "123456dfdfddfdf";
private String password = "123456";
/**
* Statment存在sql被注入的风险
*/
@Test
public void testByStatement(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//获取连接
conn = JdbcUtil.getConnection();
//创建Statment
stmt = conn.createStatement();
//准备sql
String sql = "SELECT * FROM users WHERE NAME='"+name+"' AND PASSWORD='"+password+"'";
//运行sql
rs = stmt.executeQuery(sql);
if(rs.next()){
//登录成功
System.out.println("登录成功");
}else{
System.out.println("登录失败");
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt ,rs);
}
}
/**
* PreparedStatement能够有效地防止sql被注入
*/
@Test
public void testByPreparedStatement(){
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
//获取连接
conn = JdbcUtil.getConnection();
String sql = "SELECT * FROM users WHERE NAME=?
AND PASSWORD=?";
//预编译
stmt = conn.prepareStatement(sql);
//设置參数
stmt.setString(1, name);
stmt.setString(2, password);
//运行sql
rs = stmt.executeQuery();
if(rs.next()){
//登录成功
System.out.println("登录成功");
}else{
System.out.println("登录失败");
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt ,rs);
}
}
}
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);
}
}
}
类路径读取JdbcUtil的配置文件
package gz.itcast.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* jdbc工具类
* @author APPle
*
*/
public class JdbcUtil {
private static String url = null;
private static String user = null;
private static String password = null;
private static String driverClass = null;
/**
* 静态代码块中(仅仅载入一次)
*/
static{
try {
//读取db.properties文件
Properties props = new Properties();
/**
* . 代表java命令运行的文件夹
* 在java项目下,. java命令的运行文件夹从项目的根文件夹開始
* 在web项目下。 . java命令的而运行文件夹从tomcat/bin文件夹開始
* 所以不能使用点.
*/
//FileInputStream in = new FileInputStream("./src/db.properties");
/**
* 使用类路径的读取方式
* / : 斜杠表示classpath的根文件夹
* 在java项目下,classpath的根文件夹从bin文件夹開始
* 在web项目下。classpath的根文件夹从WEB-INF/classes文件夹開始
*/
InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");
//载入文件
props.load(in);
//读取信息
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
driverClass = props.getProperty("driverClass");
//注冊驱动程序
Class.forName(driverClass);
} catch (Exception e) {
e.printStackTrace();
System.out.println("驱程程序注冊出错");
}
}
/**
* 抽取获取连接对象的方法
*/
public static Connection getConnection(){
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 释放资源的方法
*/
public static void close(Connection conn,Statement stmt){
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);
}
}
}
public static void close(Connection conn,Statement stmt,ResultSet rs){
if(rs!=null)
try {
rs.close();
} catch (SQLException e1) {
e1.printStackTrace();
throw new RuntimeException(e1);
}
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);
}
}
}
}