JDBC
1、概述:
1.1概念:
java数据库连接
1.2作用:
提供了通用访问关系型数据库的接口规范.
2、入门案例
2.1导入驱动jar包
1.复制mysql-connector-java-5.1.37-bin.jar到项目的libs目录下
2.右键–>Add As Library
2.2注册驱动
Class.forName(“com.mysql.jdbc.Driver”)
2.3获取连接
Connection conn =DriverManager.getConnection(“jdbc:mysql://localhost:3306/db2”,“root”,“1234”)
2.4编写SQL
2.5获取语句执行对象 Statement
Statement st = conn.createStatement();
2.6执行SQL
int executeUpdate(sql) 执行DML语句
Result executeQuery(sql) 执行DQL语句
2.7处理结果集(查询操作)
2.8释放资源
package com.itfenghua01;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcDemo01 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
Connection con = DriverManager.getConnection("jdbc:mysql:///demo01", "root", "root");
//sql语句
String sql = "update stu set math=100 where name ='陈墨瞳' ";
//获取执行对象
Statement sta = con.createStatement();
//执行语句
int update = sta.executeUpdate(sql);
System.out.println(update);
//释放资源
sta.close();
con.close();
}
}
3、相关的Api
3.1DriverManager ★
3.1.1注册驱动 registerDriver(Driver driver) -
3.1.2获取连接 getConnection(url,user,pwd)
1.参数url:
标准写法: jdbc:mysql://localhost:3306/数据库名称
简单写法: jdbc:mysql:///数据库名称
2.参数user: 数据库用户
3.参数pwd: 数据库密码
3.2Connection连接 ★
3.2.1获取语句执行对象
-
Statement st = conn.createStatement();
-
PreparedStatement pst = conn.preparedStatement(String sql);
3.区别:
1)PreparedStatement 防止SQL注入问题
2)执行效率更高
3)编写起来更加简单
3.2.2管理事务
-
开启事务 setAutoCommit(false);
- 提交事务 commit();
- 回滚事务 rollback();
3.3 Statement语句执行
1.int executeUpdate(String sql) 用于执行增删改的SQL语句,返回影响的行数
2.ResultSet executeQuery(String sql); 用于执行查询语句,返回结果集对象
3.4 ResultSet 结果集 ★
3.4.1作用:
封装了查询的数据
3.4.2操作
1.boolean next(); 游标向下移动一行, 若有下一行返回true,反之为false
2.getXxx(int 编号);
3.getXxx(“列名”) ★
Xxx 必须和 列类型一样
int getInt(…)
varchar getString(…)
Date getDate(…)
double getDouble(…)
package com.itfenghua01;
import java.sql.*;
public class jdbcDemo03 {
public static void main(String[] args) {
Connection con =null;
Statement sta =null;
ResultSet resultSet =null;
try {
con = DriverManager.getConnection("jdbc:mysql:///demo01", "root", "root");
String sql ="select * from stu ";
sta = con.createStatement();
resultSet = sta.executeQuery(sql);
while (resultSet.next()){
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
Date date = resultSet.getDate("time");
int math = resultSet.getInt("math");
String sex = resultSet.getString("sex");
System.out.println(name+","+age+","+date+","+math+","+sex);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
if (sta!=null)
try {
resultSet.close();
sta.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
4、PreparedStatement预处理对象 ★
4.1SQL注入问题
用户输入一些特殊字符,导致整个SQL的结构发生了改变
4.2开发步骤
1.导入jar包
2.注册驱动
-
获取连接
-
编写SQL
SELECT * FROM USER WHERE username = ? AND PASSWORD = ? ; -
获取语句执行对象 PreparedStatement
conn.preparedStatement(String sql); -
给?占位符赋值
preparedStatement.setXxx(int 问号的编号,值)
注意: ? 从 1开始的
Xxx 必须 和数据库列类型一样
7 执行SQL
8.处理结果集(查询操作)
9.释放资源
4.3操作
1.int executeUpdate() 用于执行增删改的SQL语句,返回影响的行数
2.ResultSet executeQuery(); 用于执行查询语句,返回结果集对象
package com.itfenghua02;
import com.JDBCUtils.JDBCUtils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCDemo01 {
@Test
public void add() throws SQLException {
Connection conn = JDBCUtils.getConnection();
String sql = "insert into ss VALUE(?,?)";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setInt(1,8);
pst.setInt(2,119);
pst.executeUpdate();
JDBCUtils.close(null,pst,conn);
}
@Test
public void delect() throws SQLException {
//获取连接
Connection conn = JDBCUtils.getConnection();
//sql语句
String sql = "delete from ss where id=? ";
//获取预处理对象
PreparedStatement pst = conn.prepareStatement(sql);
//给占位符赋值
pst.setInt(1,1);
//执行操作
pst.executeUpdate();
//释放资源
JDBCUtils.close(null,pst,conn);
}
@Test
public void update() throws SQLException {
Connection conn = JDBCUtils.getConnection();
String sql ="update ss set num=? where id=? ";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setInt(1,10000);
pst.setInt(2,2);
pst.executeUpdate();
JDBCUtils.close(null,pst,conn);
}
@Test
public void query() throws SQLException {
Connection conn = JDBCUtils.getConnection();
String sql = "select * from ss";
PreparedStatement pst = conn.prepareStatement(sql);
//结果集
ResultSet res = pst.executeQuery();
//遍历结果集,结果集对象,封装查询结果
while (res.next()){
int id = res.getInt("id");
int num = res.getInt("num");
System.out.println(id+","+num);
}
JDBCUtils.close(res,pst,conn);
}
}
5、事务管理
1.开启事务 setAutoCommit(false);
- 提交事务 commit();
- 回滚事务 rollback();
事务模版
6、JDBC工具类提取
package com.JDBCUtils;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
//静态代码块
//只执行一次
static {
try {
//获取集合对象
Properties prop = new Properties();
//读取配置文件:jdbc.properties
InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
//加载文件
prop.load(in);
//获取文件中的关键字值
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
driver = prop.getProperty("driver");
//1.注册驱动
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* //2.获取连接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
/**
* //释放资源
* @param res
* @param sta
* @param con
*/
public static void close(ResultSet res, Statement sta,Connection con){
if (res!=null){
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if (sta!=null){
try {
sta.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if (con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}