文章预览:
1、JDBC
1.1、数据库驱动
驱动:声卡,显卡,数据库
程序通过数据库驱动和数据库打交道
1.2、JDBC
SUN公司为了简化可开发人员的操作,提供了一个Java操作数据库规范,俗称JDBC
具体的规范实现由具体的厂商去做
对于开发人员,只需要掌握JDBC接口的操作即可
java.sql
javax.sql
还需要导入一个数据库包 mysql-connector-java-5.1.47.jar
1.3、第一个JDBC 程序(连接数据库)
创建测试数据库
CREATE DATABASE jdbcStudy CHARACTER SET utf8 COLLATE utf8_general_ci;
USE jdbcStudy;
CREATE TABLE `users`(
id INT PRIMARY KEY,
NAME VARCHAR(40),
PASSWORD VARCHAR(40),
email VARCHAR(60),
birthday DATE
);
INSERT INTO `users`(id,NAME,PASSWORD,email,birthday)
VALUES(1,'zhansan','123456','zs@sina.com','1980-12-04'),
(2,'lisi','123456','lisi@sina.com','1981-12-04'),
(3,'wangwu','123456','wangwu@sina.com','1979-12-04')
1、创建一个普通项目
2、导入数据库驱动
3、编写测试代码
package com.lesson01;
import java.sql.*;
//我的第一个jdbc程序
public class JdbcFirstDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1,加载驱动
Class.forName("com.mysql.jdbc.Driver"); //固定写法,加载驱动
//2,用户信息和url
//useUnicode=true&characterEncoding=utf8&useSSL=false 这边useSSL=false可以解决版本问题,如果时true则会报错
String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false";
String username = "root";
String password = "123456";
//3.连接成功 数据库对象,Connection代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//4,执行SQL的对象 执行sql的对象
Statement statement = connection.createStatement();
//5,执行SQL的对象去执行SQL,可能存在结果,去查看返回结果
String sql = "SELECT * FROM users";
ResultSet resultSet = statement.executeQuery(sql); //返回的结果集 封装了我们全部查询的结果
//取出结果,链表
while (resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("name="+resultSet.getObject("NAME"));
System.out.println("pwd="+resultSet.getObject("PASSWORD"));
System.out.println("email="+resultSet.getObject("email"));
System.out.println("birth="+resultSet.getObject("birthday"));
}
//6,释放连接
resultSet.close();
statement.close();
connection.close();
}
}
出现的问题
//2,用户信息和url
//useUnicode=true&characterEncoding=utf8&useSSL=false 这边useSSL=false可以解决版本问题,如果时true则会报错
String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false";
如果写成 use SSL=true 结果将会出现下面的错误:
Exception in thread “main” com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
但是在网上搜出
我IDEA版本是2020版本,MySQL是5.7.3
再经过搜索,5.7.28以后版本才真正支持ssl但应用服务器没有提供验证,所有才会出错,通过提供trust store或者关闭ssl解决
步骤总结:
- 加载驱动
- 连接数据库DriverManager
- 获得执行sql的对象 statement
- 获得返回的结果集
- 释放连接
DriverManager
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");//固定写法,加载驱动,建议使用下面的写法,上面的会加载两次
Connection connection = DriverManager.getConnection(url, username, password);
//connection代表数据库
//数据库设置自动提交
connection.setAutocommit();
//事务提交,事务回滚
connection.commit();
connection.rollback();
URL
String url = "jdbc:mysql://localhost:3306:/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false";
//MySQL ----3306
//协议://主机地址:端口:/数据库名?参数1&参数2&参数3
//oralce ----1521
//jdbc:oralce:thin:@loaclhost:1521:sid
Statement 执行SQL的对象 PrepareStatement
String sql = "select * from users";//编写一个sql语句
statement.executeQuery();//查询操作 返回Resultset
statement.executeUpdate();//更新,插入,删除都用这个 返回一个受影响的行数
statement.execute();//执行任何语句
结果集对象,封装了所有的查询结果
获得指定的数据类型
resultSet.getObject();//在不知道类型的情况使用
//具体的类型都知道
resultSet.getInt();
resultSet.getString();
resultSet.getFloat();
resultSet.getObject();
遍历,指针
resultSet.beforeFirst();//移动到最前面
resultSet.afterlLast();//移动到最后面
resultSet.next();//移动到下一个数据
resultSet.previous();//移动到前一行
resultSet.absoluet(row)//移动到制定行
释放内存:消耗资源,占用内存
//6,释放连接
resultSet.close();
statement.close();
connection.close();
1.4、statement对象(增删改查)
jdbc中的statement对象用于向数据库发送sql语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。
statement对象的execute Update方法,用于向数据库发送增删改的sql语句,executeUpdate执行完后,将返回一个整数(即增删改语句导致数据库几行数据发生了变化)
statement。executeQuery方法用于向数据库发送查询语句,executeQuery方法将返回代表查询结果的resultSet对象。
CRUD操作-create
使用executeUpdate(String sql)方法完成数据添加操作,示例:
Statement st = conn.createStatement();
String sql = "insert into user(...)values(...)";
int num = st.executeUpdate(sql);
if(num >0){
System.out.println("插入成功!");
}
CRUD操作-delete
使用executeUpdate(String sql)方法完成数据删除,示例:
Statement st = conn.createStatement();
String sql = "delete from user where id = 1";
int num = st.executeUpdate(sql);
if(num >0){
System.out.println("删除成功!");
}
CRUD操作-update
使用executeUpdate(String sql)方法完成数修改操作,示例:
Statement st = conn.createStatement();
String sql = "update user set name = '' where name = ''";
int num = st.executeUpdate(sql);
if(num >0){
System.out.println("修改成功!");
}
CRUD操作-read
使用executeUpdate(String sql)方法完成数据查询操作,示例:
Statement st = conn.createStatement();
String sql = "select *from user where id = 1";
int num = st.executeQuery(sql);
while(rs.next()){
//调用rs的相应方法映射到java对象
}
db.properties
driver=com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSl=false
username=root
password=123456
jdbcUtils.java:
package com.lesson02.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
public static String driver = null;
public static String url = null;
public static String username = null;
public 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");
//驱动只用加载一次
Class.forName(driver);
} catch (Exception 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 {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
TestInsert.java:
package com.lesson02;
import com.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestInsert {
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();//获取数据库连接
st = conn.createStatement();
String sql = "INSERT INTO users(id,`NAME`,`PASSWORD`,`email`,`birthday`)" +
"VALUES(4,'zzj','123456','123456789@qq.com','2020-10-17')";
int i=st.executeUpdate(sql);
if (i>0){
System.out.println("插入成功");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.release(conn,st,rs);
}
}
}
1.5、SQL注入
sql存在漏洞,会被攻击导致数据泄露,SQL会被拼接or
1.6、PreparedStatement对象
PreparedStatement可以防止SQL注入,效率更好
System.out.println("插入成功");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.release(conn,st,rs);
}
}
}
## 1.5、SQL注入
sql存在漏洞,会被攻击导致数据泄露,==SQL会被拼接or==
[外链图片转存中...(img-GKYUAfWs-1602913972233)]
## 1.6、PreparedStatement对象
PreparedStatement可以防止SQL注入,效率更好
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201017135424611.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3d1aHVpenpq,size_16,color_FFFFFF,t_70#pic_center)