项目代码
https://github.com/yinhai1114/Java_Learning_Code/tree/main/IDEA_Chapter25/src/com/yinhai/dao_
目录
一、JDBC概述
1.基本介绍
1. JDBC为访问不同的数据库提供了统一的接口,为使用者屏蔽了细节问题。
2. Java程序员使用JDBC,可以连接任何提供了JDBC驱动程序的数据库系统,从而完成对数据库的各种操作。
3. JDBC的基本原理(原理)
4.模拟JDBC
2.JDBC带来的好处
2. JDBC带来的好处(示意图)
3.说明:JDBC是Java提供一套用于数据库操作的接口API, Java程序员只需要面向这套接口编程即可。不同的数据库厂商,需要针对这套接口,提供不同实现。
2.JDBC API
JDBC API是一系列的接口,它统一和规范了应用程序与数据库的连接、执行SQL语句,并到得到返回结果等各类操作,相关类和接口在java.sql与javax.sql包中
二、JDBC快速入门
1.JDBC程序编写的步骤
1.注册驱动 - 加载Driver类
2.获取连接 - 得到Connection
3.执行增删改查 -发送SQL给mysql执行
4.释放资源 - 关闭相关资源
2.JDBC第一个程序
创建一个表
CREATE TABLE actor ( -- 演员表
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR (32) NOT NULL DEFAULT '',
sex CHAR(1) NOT NULL DEFAULT '女',
borndate DATETIME,
phone VARCHAR(12)
)
SELECT * FROM actor
compact middle package可以关闭分级显示
前置工作
注意 创建的驱动应当是 我们引入的jar包下的
public class Jdbc01 {
public static void main(String[] args) throws SQLException {
//1.注册驱动
Driver driver = new Driver();
//2.得到连接
//(1) jdbc:mysql:// 规定好表示协议,通过jdbc的方式连接mysql
//(2) localhost 主机,可以是ip地址
//(3) 3306 表示mysql监听的端口
//(4) hsp_db02 连接到mysql dbms 的哪个数据库
//(5) mysql的连接本质就是前面学过的socket连接
String url = "jdbc:mysql://localhost:3306/yh_db02";
//将 用户名和密码放入到Properties 对象
Properties properties = new Properties();
//说明 user和password是规定号的,后面的值根据实际情况写
properties.setProperty("user","root");//用户
properties.setProperty("password","1114");//密码
Connection connect = driver.connect(url, properties);//尝试连接
//3.执行sql
String sql = "insert into actor values(null, '刘德华', '男', '1970-11-11', '110')";//插入
// String sql = "update actor set name = '周小川' where id = 1";//修改
// String sql = "delete from actor where id = 1";
Statement statement = connect.createStatement();//这个对象可以帮助执行静态sql语句并返回其生成的结果对象
int rows = statement.executeUpdate(sql);//返回的是影响的行数
System.out.println(rows > 0 ? "成功" : "失败");
//4.关闭连接
statement.close();//用完后记得及时关闭
connect.close();
}
}
三、连接数据库的5种方式
@Test
public void connect01() throws SQLException {
Driver driver = new Driver();
String url = "jdbc:mysql://localhost:3306/yh_db02";
Properties properties = new Properties();
properties.setProperty("user","root");//用户
properties.setProperty("password","1114");//密码
Connection connect = driver.connect(url, properties);//尝试连接
System.out.println(connect);
}
@Test
public void connect02() throws SQLException, Exception {
//使用反射加载Driver类
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
String url = "jdbc:mysql://localhost:3306/yh_db02";
Properties properties = new Properties();
properties.setProperty("user","root");//用户
properties.setProperty("password","1114");//密码
Connection connect = driver.connect(url, properties);//尝试连接
System.out.println(connect);
}
@Test
public void connect03() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//创建url和user和password
String url = "jdbc:mysql://localhost:3306/yh_db02";
String user = "root";
String password = "1114";
DriverManager.registerDriver(driver);//注册driver驱动
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
1. mysql驱动5.1.6可以无需CLass.forName("com.mysql.jdbc.Driver");
2.从jdk1.5以后 使用了jdbc4,不再需要显示调用class.forName()注册驱动而是自动调用驱动jar包下META-INF\services\java.sql.Driver文本中的类名称去注册
3.建议还是写上CLass.forName
@Test
public void connect05() throws IOException, ClassNotFoundException, SQLException {
//通过Properties对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
Class.forName(driver);//加载驱动
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("" + connection);
}
@Test
public void connectTest() throws IOException, ClassNotFoundException, SQLException {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
Class.forName(driver);//加载驱动
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
// statement.executeUpdate("CREATE TABLE news(" +
// "id INT PRIMARY KEY AUTO_INCREMENT," +
// "content varchar(128))");
// statement.executeUpdate("insert into news value(null, 'hellllllllllllllllllllo1')");
// statement.executeUpdate("insert into news value(null, 'hellllllllllllllllllllo2')");
// statement.executeUpdate("insert into news value(null, 'hellllllllllllllllllllo3')");
// statement.executeUpdate("insert into news value(null, 'hellllllllllllllllllllo4')");
// statement.executeUpdate("insert into news value(null, 'hellllllllllllllllllllo5')");
statement.executeUpdate("update news set content = 'yinhaiMeow' where id = 1");
statement.executeUpdate("delete from news where id = 3");
//4.关闭连接
statement.close();//用完后记得及时关闭
connection.close();
}
四、ResultSet结果集
1.基本介绍
1.表示数据库结果集的数据表,通常通过执行查询数据库的语句生成
2. ResultSet对象保持一个光标指向其当前的数据行。 最初,光标位于第一行之前
3. next方法将光标移动到下一 行,并且由于在ResultSet对象中没有更多行时返回false ,因此可以在while循环中使用循环来遍历结果集
public class ResultSet01 {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.load(new FileInputStream("IDEA_Chapter25/src/mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
//1. 注册驱动
Class.forName(driver);//建议写上
//2. 得到连接
Connection connection = DriverManager.getConnection(url, user, password);
//3. 得到Statement
Statement statement = connection.createStatement();
//4. 组织SqL
String sql = "select id, name , sex, borndate from actor";
//执行给定的SQL语句,该语句返回单个 ResultSet对象
/*
+----+-----------+-----+---------------------+
| id | name | sex | borndate |
+----+-----------+-----+---------------------+-------+
| 4 | 刘德华 | 男 | 1970-12-12 00:00:00 |
| 5 | 周星驰 | 男 | 1990-11-11 00:00:00 |
+----+-----------+-----+---------------------+-------+
*/
/*
阅读debug 代码 resultSet 对象的结构
*/
ResultSet resultSet = statement.executeQuery(sql);
//5. 使用while取出数据
while (resultSet.next()) { // 让光标向后移动,如果没有更多行,则返回false
int id = resultSet.getInt(1); //获取该行的第1列
//int id1 = resultSet.getInt("id"); 通过列名来获取值, 推荐
String name = resultSet.getString(2);//获取该行的第2列
String sex = resultSet.getString(3);
Date date = resultSet.getDate(4);
System.out.println(id + "\t" + name + "\t" + sex + "\t" + date);
}
//6. 关闭连接
resultSet.close();
statement.close();
connection.close();
}
}
五、Statement
1.基本介绍
1. Statement对象用于执行静态SQL语句并返回其生成的结果的对象
2.在连接建立后,需要对数据库进行访问,执行命名或是SQL语句,可以通过
Statement(存在SQL注入)
PreparedStatement(预处理)
CallableStatement (存储过程)
3. Statement对象执行SQL 语句,存在SQL注入风险
4. SQL 注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的SQL语句段或命令,恶意攻击数据库。
5.要防范SQL注入,只要用PreparedStatement(从Statement拓展而来)取代Statement就可以了
-- 演示sql 注入
-- 创建一张表
CREATE TABLE admin ( -- 管理员表
NAME VARCHAR(32) NOT NULL UNIQUE,
pwd VARCHAR(32) NOT NULL DEFAULT '') CHARACTER SET utf8;
-- 添加数据
INSERT INTO admin VALUES('tom', '123');
-- 查找某个管理是否存在
SELECT *
FROM admin
WHERE NAME = 'tom' AND pwd = '123'