1.JDBC
1.概念
1.数据库驱动
驱动:声卡,显卡……
我们的程序会通过数据库驱动和数据库打交道。
2.JDBC概念
SUN公司为了简化开发人员对数据库的操作,提供了一个java操作数据库的规范,俗称JDBC。
这些规范由具体厂商去做,对于开发人员来说,我们只需要掌握JDBC接口即可。
因此我们需要导入一个数据库驱动包,下载地址:https://dev.mysql.com/downloads/
2.初识JDBC程序
在SQLyog中:
CREATE DATABASE jdbcStudy CHARACTER SET utf8 COLLATE utf8_general_ci;
USE jdbcStudy;
CREATE TABLE users(
id INT PRIMARY KEY,
`name` VARCHAR(50),
`password` VARCHAR(30),
`email` VARCHAR(60),
birthday DATE
);
INSERT INTO users(`id`,`name`,`password`,`email`,`birthday`) VALUES(1,'张三','123456','12345@q','1990-12-4'),(2,'李四','1234567','dfghj@q','2000-08-2'),(3,'赵武','3456789','gyuik@','2003-07-11');
在idea里:
-
创建一个项目
-
导入数据库驱动
- 新建一个lib目录,然后把jar包拖进来
- 右键add as library添加为库
-
编写代码
import java.sql.*; public class jdbcFirstDemo { public static void main(String[] args) throws ClassNotFoundException, SQLException { //1.加载驱动 Class.forName("com.mysql.jdbc.Driver");//固定写法,加载驱动 //2.用户信息和url //useUnicode=true支持中文编码,chaeacterEncoding=utf8避免乱码,useSSL=true使用安全的连接 String url ="jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&chaeacterEncoding=utf8&useSSL=true"; String username = "root"; String password = "1234"; //3.连接成功,数据库对象 connection代表数据库 Connection connection = DriverManager.getConnection(url,username,password); //4.执行SQL的对象 Statement Statement statement = connection.createStatement(); //5.执行SQL的对象去执行SQL,查看返回结果 String sql= "SELECT * FROM `users`"; ResultSet resultSet = statement.executeQuery(sql);//执行sql,返回的结果集,结果集中封装了我们全部查询出来的结果 while(resultSet.next()){ System.out.println("id="+resultSet.getObject("id")); System.out.println("名字="+resultSet.getObject("name")); System.out.println("密码="+resultSet.getObject("password")); System.out.println("邮箱="+resultSet.getObject("email")); System.out.println("生日="+resultSet.getObject("birthday")); System.out.println("===================="); } //6.释放连接 resultSet.close(); statement.close(); connection.close(); } }
结果:
url
String url ="jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&chaeacterEncoding=utf8&useSSL=true";
//mysql---3306
//jdbc:mysql://主机地址:端口号、数据库名字?参数1&参数2&参数3
//oralce---1521
//jdbc:oralce:thin:@localhost:1521:sid
connection
//connection就是数据库对象
connection.rollback();
connection.commit();
connection.setAutoCommit();
statement
//statement执行sql的对象
PreparedStatement preparedStatement = connection.prepareStatement();//这种更安全
Statement statement = connection.createStatement();
statement.executeQuery();//查询操作,返回结果集resultSet
statement.execute();//执行任何sql
statement.executeLargeUpdate();//更新,插入,删除都用这个,返回一个受影响的行数
resultSet
//返回结果集
//1.获得指定的数据类型
resultSet.getObject()//在不知道列类型的时候使用
resultSet.getInt();
resultSet.getFloat();
resultSet.getDouble();
resultSet.getBoolean();
resultSet.getDate();
//2.遍历,指针
resultSet.next();//移动到下一个数据
resultSet.beforeFirst();//移动到最前面
resultSet.afterLast();//移动到最后面
resultSet.previous();//移动到前一行
resultSet.absolute(row);//移动到指定行
释放资源,必须去做的
resultSet.close();
statement.close();
connection.close();//特别connection
3.statement对象
JDBC里的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。
statement对象的executeUpdate方法,用于向指定数据库发送增删改的sql语句,executeUpdate执行完成后,将会返回一个整数,即导致了数据库几行数据发生了变化。
CRUD操作-create
Statement st = conn.ceateStatement();
String sql = "insert into user(...) values(...,...)";
int num = st.executeUpdate(sql);
if(num>0){
System.out.println("插入成功!");
}
CRUD操作-delete
Statement st = conn.ceateStatement();
String sql = "delete from user where id=1";
int num = st.executeUpdate(sql);
if(num>0){
System.out.println("删除成功!");
}
CRUD操作-update
Statement st = conn.ceateStatement();
String sql = "update user set name ='' where name= ''";
int num = st.executeUpdate(sql);
if(num>0){
System.out.println("修改成功!");
}
4.提取工具类
driver = com.mysql.jdbc.Driver
url =jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&chaeacterEncoding=utf8&useSSL=true
username = root
password = 1234
package utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class jdbcUtils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
try{
//获取资源
InputStream in = jdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
//1.驱动只用加载一次就可以
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
//释放连接
public static void release(Connection conn, Statement st, ResultSet rs){
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (st != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
import utils.jdbcUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class testInsert {
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
try {
conn = jdbcUtils.getConnection();//获取数据库连接
st = conn.createStatement();//执行sql的对象
String sql= "INSERT INTO users(`id`,`name`,`password`,`email`,`birthday`) "+"VALUES(6,'程','453','12345tf@','1998-3-1')";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("成功!");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
jdbcUtils.release(conn,st,null);
}
}
}
5.sql注入的问题
sql存在漏洞,会导致数据泄露。本质就是:sql会被拼接(or)。
import utils.jdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class sqlInjection {
public static void main(String[] args) {
//login("张三","123456");正常查询-----名字:张三 密码:123456
login(" 'or' 1=1 "," 'or' 1=1");//所有的用户名和密码被全部查出
}
//登录业务
public static void login(String username ,String password){
Connection conn = null;
Statement st = null;
try {
conn = jdbcUtils.getConnection();//获取数据库连接
st = conn.createStatement();//执行sql的对象
//SELECT * FROM `users` WHERE `name`='张三' AND `password`=123456;
String sql= "SELECT * FROM `users` WHERE `name`='"+username+"' AND `password`='"+password+"'";
ResultSet resultSet = st.executeQuery(sql);//执行sql,返回的结果集,结果集中封装了我们全部查询出来的结果
while(resultSet.next()) {
System.out.println("名字:" + resultSet.getObject("name"));
System.out.println("密码:" + resultSet.getObject("password"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
jdbcUtils.release(conn,st,null);
}
}
}
6.PreparedStatement对象
它可以防止sql注入问题,并且效率更高。
import utils.jdbcUtils;
import java.sql.Connection;
import java.util.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class psInsert {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement st = null;
try {
conn = jdbcUtils.getConnection();
//区别
//使用?占位符代替具体参数
String sql = "INSERT INTO users(`id`,`name`,`password`,`email`,`birthday`) "+"VALUES(?,?,?,?,?)";
st = conn.prepareStatement(sql);//预编译sql,先写sql,但是不执行
//手动给参数赋值
st.setInt(1,8);
st.setString(2,"q");
st.setString(3,"2345");
st.setString(4,"123456d@qq.com");
//注意点:java.util.Date是java的
// java.sql.Date是数据库的
st.setDate(5,new java.sql.Date(new Date().getTime()));
//执行
int i = st.executeUpdate();
if (i>0){
System.out.println("插入成功!");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
jdbcUtils.release(conn,st,null);
}
}
}
7.使用idea连接数据库
1.连接的时候注意:要把驱动导入进去,而且还有时区问题需要到高级设置里手动添加
2.添加想要的数据库
3.导入数据库后,双击即可查看表
4.然后直接就可以修改数据,并且要提交
5.进入编写sql代码的地方
6.编写代码
8.事务
要么都成功,要么都失败。
import utils.jdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class transaction {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement st = null;
try {
conn = jdbcUtils.getConnection();
//关闭数据库的自动提交,自动会开启事务
conn.setAutoCommit(false);//开启事务
String sql1 = "update account set money = money - 100 where name = 'A' ";
st = conn.prepareStatement(sql1);
st.executeUpdate();
String sql2 = "update account set money = money + 100 where name = 'B' ";
st = conn.prepareStatement(sql2);
st.executeUpdate();
//业务完毕,提交事务
conn.commit();
System.out.println("提交成功");
} catch (SQLException throwables) {
conn.rollback();//如果失败则回滚,不写这句话,失败也会默认自动回滚
throwables.printStackTrace();
}finally {
jdbcUtils.release(conn,st,null);
}
}
}
结果:
9.数据库连接池
我们现在是数据库连接----执行----释放,但是连接释放整个过程是十分浪费资源的。因此我们要编写一个连接池,编写连接池只需要实现一个接口Datasource(接口不会变,方法就不会变)。使用了这些数据连接池之后,我们在项目开发时,就不需要编写连接数据库的编码了!
池化技术:准备一些预先的资源,过来就连准备好的:
-
开门—业务员:等待-----服务----关门
-
这里的业务员需要多少人呢?这就引出了最小连接数,这个根据你的常用连接数来设定就可以
-
最大连接数:业务最高承载上限,如果达到最高连接数,剩下的就需要排队等待了
-
等待超时:如果要等待的时间太长,直接告诉后面的走掉即可
一些常见的开源数据库连接池:
-
DBCP
-
C3P0
-
Druid:阿里巴巴的
1. DBCP
导入jar包,导入并添加为库:
-
Commons-dbcp.jar:连接池的实现
-
Commons-pool.jar:连接池实现的依赖库
-
下载地址:http://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi,http://commons.apache.org/proper/commons-pool/download_pool.cgi
#数据库驱动,连接设置:这里的名字是DBCP数据源定义好的
driverClassName=com.mysql.jdbc.Driver
#数据库连接地址
url=jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&chaeacterEncoding=utf8&useSSL=true
#用户名
username=root
#密码
password=1234
#初始化连接
initialSize=10
#连接池的最大数据库连接数。设为0表示无限制
maxActive=50
#最大空闲连接,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制
maxIdle=20
#最小空闲连接
minIdle=5
#最大建立连接等待时间,毫秒为单位。如果超过此时间将接到异常。设为-1表示无限制
maxWait=60000
#配置监控统计拦截的filters
#filters=stat
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们
connectionProperties=useUnicode=true;characterEncoding=UTF8
#指定由连接池所创建的连接的自动提交(auto-commit)状态
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
package utils;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class dbcpUtils {
private static DataSource dataSource = null;
static {
try{
//获取资源
InputStream in = dbcpUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties properties = new Properties();
properties.load(in);
//创建数据源 工厂模式--创建对象
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
//释放连接
public static void release(Connection conn, Statement st, ResultSet rs){
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (st != null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
测试DBCP代码和前面一样,只需要改一句:conn = dbcpUtils.getConnection()。
2.C3P0
导入jar包,导入并添加为库:
- c3p0-0.9.5.2.jar
- mchange-commons-java-0.2.15.jar
<?xml version="1.0" encoding="UTF-8"?>
<!--xml不用读,加载的时候自动匹配-->
<c3p0-config>
<!-- 默认配置,如果没有指定则使用这个配置 -->
<default-config>
<property name="user">root</property>
<property name="password">1234</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&chaeacterEncoding=utf8&useSSL=true</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="checkoutTimeout">30000</property>
<property name="idleConnectionTestPeriod">30</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">2</property>
<property name="maxStatements">200</property>
</default-config>
<!-- 命名的配置,可以通过方法调用实现 -->
<named-config name="MySQL">
<property name="user">root</property>
<property name="password">1234</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&chaeacterEncoding=utf8&useSSL=true</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<!-- 如果池中数据连接不够时一次增长多少个 -->
<property name="acquireIncrement">5</property>
<!-- 初始化数据库连接池时连接的数量 -->
<property name="initialPoolSize">20</property>
<!-- 数据库连接池中的最大的数据库连接数 -->
<property name="maxPoolSize">25</property>
<!-- 数据库连接池中的最小的数据库连接数 -->
<property name="minPoolSize">5</property>
</named-config>
</c3p0-config>
package utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class c3p0Utils {
private static ComboPooledDataSource dataSource = null;
static {
try{
dataSource = new ComboPooledDataSource("MySQL");
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
//释放连接
public static void release(Connection conn, Statement st, ResultSet rs){
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (st != null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
测试DBCP代码和前面一样,只需要改一句:conn = c3p0Utils.getConnection()。