一JDBC概述
Java提供的一套用来操作数据的接口
二如何获取数据库的连接
1.获取数据库连接的必要条件
/*
①数据必须是正常的在运行。
②数据库的账号和密码必须正确
③提供正确的驱动程序
*/
2.方式一:Driver
//多态:创建驱动程序的对象
Driver driver = new com.mysql.jdbc.Driver();
//获取mysql连接对象
Properties info = new Properties();
info.setProperty("user","root");//mysql账号
info.setProperty("password","123321");//mysql密码
/*
jdbc:mysql://localhost:3306/myemployees
jdbc:mysql : 协议
localhost :mysql所在的机器的ip地址
3306 :mysql的端口号
myemployees:库名
*/
String url = "jdbc:mysql://localhost:3306/myemployees";
Connection connect = driver.connect(url, info);//mysql连接地址
System.out.println(connect);
3.方式二:DriverManager
//多态:创建驱动程序的对象 -- 注意:mysql的Driver类中在静态代码块中已经注册了驱动
Driver driver = new com.mysql.jdbc.Driver();
//注册驱动
DriverManager.registerDriver(driver);
//获取连接对象
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/myemployees",
"root", "123321");
System.out.println(con);
4.方式三:读取配置文件
FileInputStream fis = null;
Connection con = null;
try {
Properties properties = new Properties();
fis = new FileInputStream("jdbc.properties");
properties.load(fis);
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
//通过读取配置文件内容获取数据库连接对象
Class.forName(driver);
//获取连接对象
con = DriverManager.getConnection(url, user, password);
System.out.println(con);
}catch (Exception e){
e.printStackTrace();
}finally {
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (con != null){
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
三 对数据库增删改查操作
/*
修改数据
*/
@Test
public void test3() throws SQLException {
//1.获取数据库接对象
Connection connection = JDBCUtils.getConnection();
//2.预编译
String sql = "update s set age=? where id=?";
PreparedStatement ps = connection.prepareStatement(sql);
//3.给占位符赋值
ps.setInt(2,1);
ps.setInt(1,28);
//4.执行sql语句
int i = ps.executeUpdate();
System.out.println(i + "条受到影响");
//5.关闭资源
JDBCUtils.close(connection,ps);
}
/*
删除数据
*/
@Test
public void test2() throws SQLException {
//1.获取数据库接对象
Connection connection = JDBCUtils.getConnection();
//2.预编译
String sql = "delete from s where id=?";
PreparedStatement ps = connection.prepareStatement(sql);
//3.给占位符赋值
ps.setInt(1,1);
//4.执行sql语句
int i = ps.executeUpdate();
System.out.println(i + "条受到影响");
//5.关闭资源
JDBCUtils.close(connection,ps);
}
/*
插入数据
*/
@Test
public void test() throws SQLException {
//1.获取数据库连接对象
Connection connection = JDBCUtils.getConnection();
//2.预编译
String sql = "insert into s(id,name,age) values(?,?,?)";//数据用?替代。?叫作占位符
PreparedStatement ps = connection.prepareStatement(sql);
//3.给占位符设置数据
//setInt(int parameterIndex, int x) : 第一个参数:第几个占位符 第二个参数:设置的数据
ps.setInt(1,2);
ps.setString(2,"longge");
ps.setInt(3,20);
//4.执行sql语句
/*
executeUpdate() :用来执行 增,删,改的操作 返回所影响数据的条数
*/
int i = ps.executeUpdate();
System.out.println(i + "条受到影响");
//5.关资源
JDBCUtils.close(connection,ps);
}
/*
获取多行数据
*/
public List<Student> getStudents() throws SQLException {
Connection connection = JDBCUtils.getConnection();
PreparedStatement ps =
connection.prepareStatement("select id,name,age from s");
/*
executeQuery() : 执行查询语句
*/
ResultSet resultSet = ps.executeQuery();
//创建一个集合用来存对象
List<Student> list = new ArrayList<>();
//遍历数据
while(resultSet.next()){//判断是否有数据
//获取数据
//getInt(String columnLabel) : 参数是字段名称
//getInt(int columnIndex) :参数是字段的索引
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
//封装成对象
list.add(new Student(id,name,age));
}
//关闭资源
JDBCUtils.close(connection,ps,resultSet);
return list;//没有数据就return null
}
/*
获取单行数据
*/
public Student getStudent() throws SQLException {
Connection connection = JDBCUtils.getConnection();
PreparedStatement ps =
connection.prepareStatement("select id,name,age from s where id=?");
ps.setInt(1,2);
/*
executeQuery() : 执行查询语句
*/
ResultSet resultSet = ps.executeQuery();
//遍历数据
while(resultSet.next()){//判断是否有数据
//获取数据
//getInt(String columnLabel) : 参数是字段名称
//getInt(int columnIndex) :参数是字段的索引
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
//封装成对象
return new Student(id,name,age);
}
//关闭资源
JDBCUtils.close(connection,ps,resultSet);
return null;//没有数据就return null
}
四 SQL注入
五 批处理
(1)在url中加一个参数
jdbc:mysql://localhost:3306/myemployees?rewriteBatchedStatements=true
(2)调用方法
//添加到批处理中
ps.addBatch();
//执行sql语句
ps.executeBatch();
//清空批处理
ps.clearBatch();
(2)代码
//1.获取数据库的连接对象
Connection connection = JDBCUtils.getConnection();
//2.预编译
String sql = "insert into s(id,name,age) values(?,?,?)";
PreparedStatement ps = connection.prepareStatement(sql);
//3.设置数据
for (int i = 1; i <= 100000; i++) {
ps.setInt(1,i);
ps.setString(2,i+"");
ps.setInt(3,i);
//添加到批处理中
ps.addBatch();
if (i % 1000 == 0) {
//执行sql语句
ps.executeBatch();
//清空批处理
ps.clearBatch();
}
}
//4.关闭资源
JDBCUtils.close(connection,ps);
六 事务
/*
事务的ACID(acid)属性
1. 原子性(Atomicity):原子性是指事务是一个不可分割的工作单位,事务中的操作要么都发生,要么都不发生。
2. 一致性(Consistency):事务必须使数据库从一个一致性状态变换到另外一个一致性状态。
3. 隔离性(Isolation):事务的隔离性是指一个事务的执行不能被其他事务干扰,即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。
4. 持久性(Durability):持久性是指一个事务一旦被提交,它对数据库中数据的改变就是永久性的,接下来的其他操作和数据库故障不应该对其有任何影响
*/
//1.获取数据库连接对象
Connection connection = JDBCUtils.getConnection();
//2.禁止自动提交
connection.setAutoCommit(false);
try{
//3.转账的操作
String sql = "update account set balance=? where account=?";
PreparedStatement ps = connection.prepareStatement(sql);
//设置1100的账户
ps.setInt(1,900);
ps.setInt(2,1100);
ps.executeUpdate();
System.out.println(1 / 0);
//设置2200的账户
ps.setInt(1,1100);
ps.setInt(2,2200);
ps.executeUpdate();
//提交
connection.commit();
}catch (Exception e){
e.printStackTrace();
//事务回滚
connection.rollback();
}finally {
//把禁止提交恢复原来的状态
connection.setAutoCommit(true);
if (connection != null){
connection.close();
}
}
七 连接池
1、什么是数据库连池
连接对象的缓冲区。负责申请,分配管理,释放连接的操作。
2、为什么要使用数据库连接池
通过DriverManager获取新连接,用完直接抛弃断开,连接的利用率太低,太浪费。
对于数据库服务器来说,压力太大了。
3、阿里的德鲁伊连接池技术
/*
方式二 : 读取配置文件的方式
注意:配置文件中的key不能随意修改
url=jdbc:mysql://localhost:3306/myemployees
username=root
password=123321
driverClassName=com.mysql.jdbc.Driver
*/
@Test
public void test2() throws Exception {
//1.创建Properties的对象
Properties p = new Properties();
//2.加载流
p.load(new FileInputStream("druid.properties"));
//3.创建DataSource的对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(p);
//4.获取连接对象
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
/*
方式一
*/
@Test
public void test() throws SQLException {
//创建DruidDataSource的对象
DruidDataSource ds = new DruidDataSource();
//设置参数
ds.setUrl("jdbc:mysql://localhost:3306/myemployees");
ds.setUsername("root");
ds.setPassword("123321");
ds.setDriverClassName("com.mysql.jdbc.Driver");
//获取连接对象
Connection connection = ds.getConnection();
System.out.println(connection);
}
八 JDBCUtils
1.配置文件内容
/*
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/myemployees?rewriteBatchedStatements=true
user=root
password=123321
*/
2.代码
public class JDBCUtils {
private static FileInputStream fis = null;
private static String driver = null;
private static String url = null;
private static String user = null;
private static String password = null;
/*
静态代码块 :读取配置文件中的内容
*/
static{
try {
Properties properties = new Properties();
fis = new FileInputStream("jdbc.properties");
properties.load(fis);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
//通过读取配置文件内容获取数据库连接对象
Class.forName(driver);
}catch (Exception e){
e.printStackTrace();
}finally {
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static Connection getConnection(){
//获取连接对象
Connection con = null;
try {
con = DriverManager.getConnection(url, user, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return con;
}
public static void close(Connection connection, PreparedStatement ps, ResultSet rs) {
close(connection,ps);
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(Connection connection, PreparedStatement ps) {
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ps != null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
九 DBUtils
public class DBUtilsTest {
/*
使用DBUtils实现增,删,改,查的功能
*/
/*
查询数据
注意:Javabean中的字段名称和类型必须和表中的字段类型保持一致。
如果Javabean中的字段名和表中的字段名不一一致,可以采用别名的方式进行解决。
*/
@Test
public void test4() throws SQLException {
//创建QueryRunner的对象
QueryRunner queryRunner = new QueryRunner();
//sql语句
String sql = "select id as sid,name,age from s where id = ?";
Student student = queryRunner.query(JDBCUtils.getConnection(), sql,
new BeanHandler<Student>(Student.class), 1);
System.out.println(student);
}
@Test
public void test5() throws SQLException {
//创建QueryRunner的对象
QueryRunner queryRunner = new QueryRunner();
//sql语句
String sql = "select id,name,age from s";
List<Student> query = queryRunner.query(JDBCUtils.getConnection(), sql,
new BeanListHandler<Student>(Student.class));
//遍历
for (Student s : query) {
System.out.println(s);
}
}
/*
修改数据
*/
@Test
public void test3() throws SQLException {
//创建QueryRunner的对象
QueryRunner queryRunner = new QueryRunner();
//update()用来执行增,删,改的方法
String sql = "update s set name=? where id=?";
int update = queryRunner.update(JDBCUtils.getConnection(), sql,"cang",1);
System.out.println(update + "条数据受到影响");
}
/*
添加数据
*/
@Test
public void test2() throws SQLException {
//创建QueryRunner的对象
QueryRunner queryRunner = new QueryRunner();
//update()用来执行增,删,改的方法
String sql = "insert into s(id,name,age) values(?,?,?)";
int update = queryRunner.update(JDBCUtils.getConnection(), sql,3,"long",30);
System.out.println(update + "条数据受到影响");
}
/*
删除
*/
@Test
public void test() throws SQLException {
//创建QueryRunner的对象
QueryRunner queryRunner = new QueryRunner();
//update()用来执行增,删,改的方法
String sql = "delete from s";
int update = queryRunner.update(JDBCUtils.getConnection(), sql);
System.out.println(update + "条数据受到影响");
}
}
529

被折叠的 条评论
为什么被折叠?



