JDBC
获取连接的五种方式
-
方式一
public class TestConnection2 { public void test1() throws Exception { // 1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); // 2.获取连接 Connection connection = DriverManager.getConnection("jdbc:mysql:///girls?user=root&password=root"); System.out.println(connection); }
-
方式二
public void test2() throws Exception { // 1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); // 2.获取连接 Connection connection = DriverManager.getConnection("jdbc:mysql:///girls", "root", "root"); System.out.println(connection); }
-
方式三
public void test3() throws Exception { // 1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); // 2.获取连接 Properties info = new Properties(); info.load(new FileInputStream("src/db.properties")); Connection connection = DriverManager.getConnection("jdbc:mysql:///girls", info); System.out.println(connection); }
创建db.properties 文件
user=root password=root driverClass=com.mysql.jdbc.Driver url=jdbc:mysql:///girls #url=jdbc:mysql://127.0.0.1:3306/girls
-
方式四
public void test4() throws Exception { Properties info = new Properties(); info.load(new FileInputStream("src/db.properties")); String driverClass = info.getProperty("driverClass"); String url = info.getProperty("url"); String user = info.getProperty("user"); String password = info.getProperty("password"); // 1.加载驱动 Class.forName(driverClass); // 2.获取连接 Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection); }
-
方式五
public class TestConnection01 { public static void main(String[] args) throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/girls?serverTimezone=UTC"; Connection connection = DriverManager.getConnection(url, "root", "YingGu123456!"); System.out.println(connection); } } //尖叫提示:方式五主要是连接mysql8.0.19数据库
JDBC相关API
-
DriverManager 驱动管理类
registerDriver 加载驱动(不建议用)
getConnection 获取连接(提供了三种方式) -
Connection 连接接口
createStatement() 获取命令对象
prepareStatement(sql) 获取预编译命令对象 -
Statement 命令 接口
execute(sql):执行任何sql语句,返回是否为结果集
executeQuery(sql):执行查询sql语句,返回ResultSet结果集对象
executeUpdate(sql):执行增删改sql语句,返回受影响的行数 -
PreparedStatement 预编译命令 接口
execute():执行任何sql语句,返回是否为结果集
executeQuery():执行查询sql语句,返回ResultSet结果集对象
executeUpdate():执行增删改sql语句,返回受影响的行数
setXX(占位符索引,占位符的值):设置该占位符的值,索引从1开始,值的类型为XX
setObject(占位符索引,占位符的值):设置该占位符的值,索引从1开始,值的类型为Object -
ResultSet 结果集接口
next():下移一行,并返回该行是否有值
previous():上移一行,并返回该行是否有值
getXX(列索引):根据列索引获取该列值,返回类型为XX。索引从1开始
getObject(列索引):根据列索引获取该列值,返回类型为Object。索引从1开始
getXX(列名):根据列名获取该列值,返回类型xx
getObject(列名):根据列名获取该列值,返回类型Object
mysql图片的上传和下载
1.BLOB类型
MySQL中,BLOB是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。
MySQL的四种BLOB类型(除了在存储的最大信息量上不同外,它们是等同的)
实际使用中根据需要存入的数据大小定义不同的BLOB类型。
需要注意的是:如果存储的文件过大,数据库的性能会下降。
2.图片上传
public class TestBlob {
@Test
public void testSave() throws Exception {
// 1.获取连接
Connection connection = JDBCUtils.getConnection();
// 2.执行
PreparedStatement statement = connection.prepareStatement("update beauty set photo=? where id=?");
InputStream inputStream = new FileInputStream("\\图片位置");
statement.setBlob(1, inputStream);
statement.setInt(2, 5);
int update = statement.executeUpdate();
System.out.println(update > 0 ? "success" : "failure");
// 3.关闭
inputStream.close();
JDBCUtils.closeConnection(null, statement, connection);
}
}
3.图片下载
@Test
public void testRead() throws Exception {
// 1.获取连接
Connection connection = JDBCUtils.getConnection();
// 2.访问数据库
PreparedStatement statement = connection.prepareStatement("select photo from beauty where id=?");
statement.setInt(1, 5);
ResultSet set = statement.executeQuery();
if (set.next()) {
// 方式一:getBlob
// Blob blob = set.getBlob(1);
// InputStream inputStream = blob.getBinaryStream();
// 方式二:getBinaryStream
InputStream inputStream = set.getBinaryStream(1);
// 写入到指定的文件中——写入到src\copy.jpg
FileOutputStream fos = new FileOutputStream("src\\copy.jpg");
int len;
byte[] b = new byte[1024];
while ((len = inputStream.read(b)) != -1) {
fos.write(b, 0, len);
}
fos.close();
inputStream.close();
}
// 3.关闭
JDBCUtils.closeConnection(set, statement, connection);
}
注意点
(1)图片选小的
(2)编码格式是不是utf-8
(3) Stream 流别忘记关闭
·
·
批量处理jdbc 语句提高处理速度
注意事项:
(1)使用批处理,首先选对驱动包,5.1.37是可以的,5.1.7 是不可以的
jar包不同,批处理支持的程度不同
(2)开启批处理
#url=jdbc:mysql:///orcl?rewriteBatchedStatements=true&useServerPrepStmts=false
代码部分:
@Test
public void testUseBatch() throws Exception {
// 1.获取连接
Connection connection = JDBCUtils.getConnection();
// 2.访问数据库
PreparedStatement statement = connection.prepareStatement("insert into admin values(null,?,?)");
for (int i = 1; i < 50000; i++) {
statement.setString(1, "小花" + i);
statement.setString(2, "8888");
// 批处理
statement.addBatch();// 将要执行的sql语句添加到批处理包(装篮子的操作)
if (i % 1000 == 0) {
statement.executeBatch();// 提交批处理的命令们(上楼运篮子的操作)
statement.clearBatch();// 清空批处理包(卸篮子的操作)
} else if (i > 49000) {
statement.executeBatch();// 提交批处理的命令们(上楼运篮子的操作)
statement.clearBatch();// 清空批处理包(卸篮子的操作)
}
}
// 3.关闭
JDBCUtils.closeConnection(null, statement, connection);
}
事务
案例一:
@Test
public void testUseTransaction1() {
// 1.获取连接
Connection connection = null;
PreparedStatement statement = null;
try {
connection = JDBCUtils.getConnection();
// 2.访问
// 事务使用步骤1:开启事务
connection.setAutoCommit(false);
statement = connection.prepareStatement("update account set balance = ? where username=?");
// 更新张三丰的余额
statement.setFloat(1, 500);
statement.setString(2, "张三丰");
statement.executeUpdate();
// 演示异常
// int i = 1 / 1;
int i = 1 / 0;
// 更新郭襄的余额
statement.setFloat(1, 1500);
statement.setString(2, "郭襄");
statement.executeUpdate();
// 事务使用步骤2:提交
connection.commit();
} catch (Exception e) {
// 事务使用步骤3:回滚
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
try {
// 3.关闭
JDBCUtils.closeConnection(null, statement, connection);
} catch (Exception e) {
e.printStackTrace();
}
}
}
案例二
/**
* 明明开始 事务, 却没有达到事务数据的一直性 原因是,使用工具类,开始连接事务的连接和执行语句的连接不是一个连接
注意: 开启事务的连接对象和事务执行语句的连接对象必须是同一个!!!
*/
@Test
public void testUseTransaction2() {
// 1.获取连接
Connection connection = null;
try {
connection = JDBCUtils.getConnection();
// 2.访问
// 事务使用步骤1:开启事务
connection.setAutoCommit(false);
// 事务的操作1:更新张三丰
MyCRUDUtils.update(connection, "update account set balance = ? where username=?", 500, "张三丰");
// MyCRUDUtils.update( "update account set balance = ? where
// username=?", 500, "张三丰");
// 模拟异常
int i = 1 / 0;
// 事务的操作1:更新郭襄
MyCRUDUtils.update(connection, "update account set balance = ? where username=?", 1500, "郭襄");
// 事务使用步骤2:提交
connection.commit();
} catch (Exception e) {
// 事务使用步骤3:回滚
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
try {
// 3.关闭
JDBCUtils.closeConnection(null, null, connection);
} catch (Exception e) {
e.printStackTrace();
}
}
}