JDBC
文章目录
一、简介
JDBC:Java DateBase Connectivity (java连接数据库规范)
二、连接mysql数据库
命令行:
mysql -h -u root -p password;
使用库
命令行方式
可视化工具
- Mysql Workbench
- Navicate Premium
- …
对表进行操作
同上
三、JDBC连接数据库
1、加载驱动:反射 Driver
-
class.forName("com.mysql.jdbc.Driver");
2、连接数据库
-
DriverManager.getConnection(url,usename,password);
- username:用户名
- password:密码
-
url: jdbc:mysql://127.0.0.1:3306/databasename;
- jdbc:主协议
- mysql:子协议
- 127.0.0.1:代表本地 localhost
- 3306:端口号
- databasename:数据库名称
3、获取发送sql语句的对象
- Statement :普通对象
- PreparedStatment: 预编译、是statment的子类
4、获取结果集
- ResultSet:查询操作结果集
- int:增删改操作结果集(返回影响的行数)
5、关闭资源
- close() 先开后闭
四、JDBC连接数据库操作
1、导入jar包
-
mysql-connector-java-5.1.47
- 5.x版本下的驱动语句为:
Class.forName("com.mysql.jdbc.Driver");
-
mysql-connector-java-8.0.27
- 8.x版本下的驱动语句为:
Class.forName("com.mysql.cj.jdbc.Driver");
-
url语句
在url语句的数据库名后添加以下示例
- characterEncoding:编码格式
- useSSL:是否使用安全连接
- severTimezone:设置时区
String url="jdbc:mysql://localhost:3306/db_book?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";
2、DButils工具类
可减少一些工作量
package com.liaoliaonan.utils;
import com.sun.corba.se.pept.transport.ConnectionCache;
import java.sql.*;
public class DBUtils {
//static 静态代码块 静态方法(不能调用普通方法)也很高 加载的优先级很高
//类中存在静态方法,可通过 类名.方法名的方式直接使用
static {
//静态代码块
try {
//加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* 获取资源
* 获取数据库对象
* @return java.sql.connection 数据库连接对象
*/
public static Connection getConnection(){
Connection connection=null;
try {
//try 捕获 发生异常时,此部分代码停止运行,并不会影响其他部分
String url="jdbc:mysql://localhost:3306/db_book?";
String username="root";
String password="haonan7412963..";
connection=DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
throw new RuntimeException(e);
//异常处理
}
return connection;
}
/**
* 释放资源
* @param statement 发送sql语句对象
* @param connection 数据库连接对象
* 无返回值
*/
public static void closeAll(Statement statement, Connection connection) {
try {
if(statement!=null){
statement.close();
}
if(connection!=null){
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 释放资源
* @param resultSet 返回结果集对象
* @param statement 发送sql语句对象
* @param connection 数据库连接对象
*/
public static void closeAll(ResultSet resultSet,Statement statement, Connection connection) {
try {
if (resultSet!=null){
resultSet.close();
}
if(statement!=null){
statement.close();
}
if(connection!=null){
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
3、数据库插入(用了工具类Util)
package com.liaoliaonan.www;
import com.baidu.utils.DBUtils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TextJDBC {
public static void main(String[] args) throws SQLException {
// //加载驱动
// try {
// Class.forName("com.mysql.cj.jdbc.Driver");
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// //2.获取数据库连接
// String url="jdbc:mysql://localhost:3306/db_book";
// String username="root";
// String password="haonan7412963..";
// Connection connection= DriverManager.getConnection(url,username,password);
// System.out.println("数据库连接对象"+connection);
Connection connection=DBUtils.getConnection();
//3,发送sql语句的对象
Statement statement=connection.createStatement();
int update=statement.executeUpdate("insert into test_stu(username,password,sex)values ('赵琛洋','1212','man')");
//4,获取结果集对象
if(update==1){
System.out.println("插入成功!");
}
else{
System.out.println("插入失败!");
}
//5,关闭资源
// statement.close();
// connection.close();
DBUtils.closeAll(statement,connection);
}
}
4、数据库查找(没用工具类Util)
package com.liaoliaonan.www;
import java.sql.*;
public class TestSelect {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/db_book","root","haonan7412963..");
Statement statement=connection.createStatement();
//获取结果集对象
ResultSet resultSet=statement.executeQuery("select *from test_stu");
//解析数据
while(resultSet.next()){
//next() 判断有无下一个元素 相当于迭代器,游标。
String username=resultSet.getString("username");
String password=resultSet.getString("password");
String sex=resultSet.getString("sex");
int id=resultSet.getInt("id");
System.out.println(id+" "+username+" "+password+" "+sex+" ");
//5,关闭资源
resultSet.close();
statement.close();
connection.close();
}
}
}
五、SQL注入
用户输入的数据中含有数据库语言的关键字,改变了sql最终运行的结果,使条件恒为true的状态。
- 解决方法:在用户输入条件之前,代码已经完成对sql语句的编译。
PreparedStatement
-
继承了Statement对象
-
作用:
-
对sql进行预编译,防止sql注入。
-
运行速度比statement快。
-
package com.liaoliaonan.www; import com.baidu.utils.DBUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class TestPrepared { public static void main(String[] args) throws SQLException { Connection connection=DBUtils.getConnection(); PreparedStatement preparedStatement=connection.prepareStatement("select * from test_stu where id =?"); //parameterIndex 设置值的下标 从1开始 //x是具体数据 preparedStatement.setInt(1,1); ResultSet resultSet=preparedStatement.executeQuery(); while(resultSet.next()){ //next() 判断有无下一个元素 相当于迭代器,游标。 String username=resultSet.getString("username"); String password=resultSet.getString("password"); String sex=resultSet.getString("sex"); int id=resultSet.getInt("id"); System.out.println(id+" "+username+" "+password+" "+sex+" "); } //虽然closeALL中是statement为参数但preparedStatement是其子类可以使用,多态性 DBUtils.closeAll(resultSet,preparedStatement,connection); } }
-
六、Druid数据库连接池
1、使用
- druid-1.1.20.jar放入lib文件夹下
- 添加db.properties文件放在src文件夹下
提供一个容器,容器中盛放的是提前准备好的链接库连接对象,使用时,直接从容器中获取,使用结束后,重新放回容器。
- 作用
- 效率更高,减少了对数据库的访问
- 资源占用率会降低
#db.properties文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_book
username=root
password=haonan7412963..
#最大数据库连接数量
#初始化数量
#最小数据库连接数量
#等等
2、实现
package com.liaoliaonan.www;
import com.alibaba.druid.util.JdbcUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class TestDruid {
public static void main(String[] args) throws IOException {
//加载配置文件
Properties properties=new Properties();
//加载db.properties
InputStream is= JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
//读取db.properties 通过properties对象,将流中的信息分割成键值对
properties.load(is);
String driver=properties.getProperty("driver");
String url=properties.getProperty("url");
}
}
3、使用Druid连接池的DButils工具类
package com.liaolnan.utils;
import com.alibaba.druid.util.JdbcUtils;
import com.sun.corba.se.pept.transport.ConnectionCache;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class DBUtils {
//static 静态代码块 静态方法(不能调用普通方法)也很高 加载的优先级很高
//类中存在静态方法,可通过 类名.方法名的方式直接使用
private static final Properties PROPERTIES=new Properties();//配置文件对象
static {
//静态代码块
InputStream resourceAsStream=JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
// try {
// //加载数据库驱动
// Class.forName("com.mysql.cj.jdbc.Driver");
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
try {
PROPERTIES.load(resourceAsStream);
Class.forName(PROPERTIES.getProperty("driver"));
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* 获取资源
* 获取数据库对象
* @return java.sql.connection 数据库连接对象
*/
public static Connection getConnection(){
Connection connection=null;
try {
//try 捕获 发生异常时,此部分代码停止运行,并不会影响其他部分
// String url="jdbc:mysql://localhost:3306/db_book?";
// String username="root";
// String password="haonan7412963..";
connection=DriverManager.getConnection(PROPERTIES.getProperty("url"),
PROPERTIES.getProperty("username"), PROPERTIES.getProperty("password"));
} catch (SQLException e) {
throw new RuntimeException(e);
//异常处理
}
return connection;
}
/**
* 释放资源
* @param statement 发送sql语句对象
* @param connection 数据库连接对象
* 无返回值
*/
public static void closeAll(Statement statement, Connection connection) {
try {
if(statement!=null){
statement.close();
}
if(connection!=null){
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 释放资源
* @param resultSet 返回结果集对象
* @param statement 发送sql语句对象
* @param connection 数据库连接对象
*/
public static void closeAll(ResultSet resultSet,Statement statement, Connection connection) {
try {
if (resultSet!=null){
resultSet.close();
}
if(statement!=null){
statement.close();
}
if(connection!=null){
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}