JDBC
1.数据库驱动
驱动:声卡,显卡,数据库
我们的程序会通过 数据库驱动,和数据库打交道!
2.JDBC
SUN公司为了简化开发人员的(对数据库的统一操作)操作,提供了一个(Java操作数据库的)规范,俗称JDBC
这些规范的实现由具体的厂商去做
对于开发人员来说,我们只需要去掌握JDBC接口的操作即可!
java.sql javax.sql 还需要导入一个数据库驱动包 mysql-connector-java-8.0.28
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,'zhangsan','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')
SELECT *FROM users
-
-
创建一个普通项目
-
导入数据库驱动
-
编写代码测试
-
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;
public class JdbcFristDemo01 {
public static void main(String[] args) throws SQLException {
//1.加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //固定写法,加载驱动
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//2.用户信息和url
String url="jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username="root";
String password="123456";
//3.连接成功,数据库对象
Connection connection=null;
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
//4.执行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"));
System.out.println("============================================");
}
//6.释放连接
resultSet.close();
statement.close();
connection.close();
}
}
4.statement对象
jdbc中的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要对这个对象向数据库发送增删改查语句即可。
statement对象的excuteUpdate方法,用于向数据库发送增删改的sql语句,excuteUpdate执行完后,将会返回一个整数(即增删改语句导致了数据库几行数据发生了变化)
Statement.excuteQuery方法用于数据库发送查询语句,excuteQuery方法返回代表查询结果的ResultSet对象
1.提取工具类和配置的文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=123456
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.propperties");
Properties properties = new Properties();
properties.load(in);
driver=properties.getProperty("driver");
url=properties.getProperty("url");
username=properties.getProperty("username");
password=properties.getProperty("password");
//1.驱动只用加载一次
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}catch (IOException 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 e) {
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
2.增删
public class TestInsert {
public static void main(String[] args) {
//1.加载驱动获取连接
Connection connection=null;
Statement st=null;
ResultSet rs=null;
try {
connection=JdbcUtils.getConnection();
st= connection.createStatement();
String sql="INSERT INTO users(id,NAME,PASSWORD,email,birthday) " +
" VALUES('4','shisan','111111','shisan@.com','2000-2-3')";
int i = st.executeUpdate(sql);
if(i>0){
System.out.println("执行成功");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.release(connection,st, rs);
}
}
}
public class TestDelect {
public static void main(String[] args) {
//1.加载驱动获取连接
//1.加载驱动获取连接
Connection connection=null;
Statement st=null;
ResultSet rs=null;
try {
connection=JdbcUtils.getConnection();
st=connection.createStatement();
String sql=" DELETE FROM users WHERE id=4";
int i=st.executeUpdate(sql);
if(i>0){
System.out.println("执行成功");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.release(connection,st,rs);
}
}
}
5.sql注入问题
sql存在漏洞,会被攻击导致数据泄露, SQL会被拼接 or
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;
public class JdbcFristDemo01 {
public static void main(String[] args) throws SQLException {
//1.加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //固定写法,加载驱动
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//2.用户信息和url
String url="jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username="root";
String password="123456";
//3.连接成功,数据库对象
Connection connection=null;
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
//4.执行sql对象
Statement statement = connection.createStatement();
//5.执行SQL的对象去执行SQL,可能存在结果,查看返回结果
//''or '1=1' 盗取所以数据
String sql="SELECT *FROM users where `NAME`=''or '1=1' AND `PASSWORD`=''or '1=1'";
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"));
System.out.println("============================================");
}
//6.释放连接
resultSet.close();
statement.close();
connection.close();
}
}
6.PreparedStatement对象
PreparedStatement可以防止SQL注入,效率更好。
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
public class TestInsert {
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,4);
st.setString(2,"shisan");
st.setString(3,"1234560");
st.setString(4,"shisan@qq.com");
st.setDate(5,new java.sql.Date(new Date().getTime()));
//执行
int row=st.executeUpdate();
if(row>0){
System.out.println("添加成功");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.release(conn,st,null);
}
}
}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestSelect {
public static void main(String[] args) {
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
try {
conn=JdbcUtils.getConnection();
String sql="SELECT *FROM users where id=?"; //编写sql
st=conn.prepareStatement(sql); //预编译
st.setInt(1,1); //传递参数
rs=st.executeQuery(); //执行
while (rs.next()){
System.out.println("id:"+rs.getInt("id"));
System.out.println("name:"+rs.getString("NAME"));
System.out.println("password:"+rs.getString("PASSWORD"));
System.out.println("email:"+rs.getString("email"));
System.out.println("birthday:"+rs.getString("birthday"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.release(conn,st,rs);
}
}
}