JavaWeb之JDBC
Posted 达少Rising
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaWeb之JDBC相关的知识,希望对你有一定的参考价值。
知识回顾:
JavaWeb之Java基础知识增强
文章目录
1.概念
- 概念:Java DataBase Connectivity Java 数据库连接, Java语言操作数据库
- JDBC本质:其实是官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口。各个数据库厂商去实现这套接口,提供数据库驱动jar包。我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类。
2. 快速入门:
2.1 步骤:
- 导入驱动jar包 mysql-connector-java-5.1.37-bin.jar
- 复制mysql-connector-java-5.1.37-bin.jar到项目的libs目录下
- 右键–>Add As Library
- 注册驱动
- 获取数据库连接对象 Connection
- 定义sql
- 获取执行sql语句的对象 Statement
- 执行sql,接受返回结果
- 处理结果
- 释放资源
2.2 代码实现
//1. 导入驱动jar包
//2.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//3.获取数据库连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "root");
//4.定义sql语句
String sql = "update account set balance = 500 where id = 1";
//5.获取执行sql的对象 Statement
Statement stmt = conn.createStatement();
//6.执行sql
int count = stmt.executeUpdate(sql);
//7.处理结果
System.out.println(count);
//8.释放资源
stmt.close();
conn.close();
package com.weeks.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
/**
* JDBC 的快速入门
*/
public class JDBCDemo
public static void main(String[] args) throws Exception
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取链接
String url = "jdbc:mysql://localhost:3306/javaweb";
String username = "root";
String password = "root123";
Connection conn = DriverManager.getConnection(url, username, password);
//3.定义sql
String sql = "update user set name='rising' where id=202101";
//4.获取执行sql的对象
Statement statement = conn.createStatement();
//5.执行sql语句
int i = statement.executeUpdate(sql);
//6.处理结果
System.out.println(i);
//8.释放资源
statement.close();
conn.close();
3.详解各个对象
3.1 DriverManager:驱动管理对象
- 功能:
- 注册驱动:告诉程序该使用哪一个数据库驱动jar
static void registerDriver(Driver driver) :注册与给定的驱动程序 DriverManager 。
- 写代码使用:
Class.forName("com.mysql.jdbc.Driver");
- 通过查看源码发现:在com.mysql.jdbc.Driver类中存在静态代码块
- 注册驱动:告诉程序该使用哪一个数据库驱动jar
static
try
java.sql.DriverManager.registerDriver(new Driver());
catch (SQLException E)
throw new RuntimeException("Can't register driver!");
注意:mysql5之后的驱动jar包可以省略注册驱动的步骤。
- 获取数据库连接:
- 方法:
static Connection getConnection(String url, String user, String password)
- 参数:
- url:指定连接的路径
- 语法:jdbc:mysql://ip地址(域名):端口号/数据库名称
- 例子:jdbc:mysql://localhost:3306/db3
- 细节:如果连接的是本机mysql服务器,并且mysql服务默认端口是3306,则url可以简写为:jdbc:mysql:///数据库名称
- user:用户名
- password:密码
- 方法:
3.2 Connection:数据库连接对象
- 功能:
- 获取执行sql 的对象
- Statement createStatement()
- PreparedStatement prepareStatement(String sql)
- 获取执行sql 的对象
- 管理事务:
- 开启事务:setAutoCommit(boolean autoCommit) :调用该方法设置参数为false,即开启事务
- 提交事务:commit()
- 回滚事务:rollback()
3.3 Statement:执行sql的对象
- 执行sql
- boolean execute(String sql) :可以执行任意的sql 了解
- int executeUpdate(String sql) :执行DML(insert、update、delete)语句、DDL(create,alter、drop)语句
- 返回值:影响的行数,可以通过这个影响的行数判断DML语句是否执行成功 返回值>0的则执行成功,反之,则失败。
- ResultSet executeQuery(String sql) :执行DQL(select)语句
- 练习:
- account表 添加一条记录
- account表 修改记录
- account表 删除一条记录
package com.weeks.jdbc;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* jdbc增删改测试
*/
public class JDBCDemo2
@Test
public void testInsert()
Statement stmt = null;
Connection conn = null;
try
//1.导入驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db2", "root", "root123");
//3.定义sql语句
String sql = "insert into account (name, balance) values ('wangwu', 2000)";
//4.定义执行sql的对象
stmt = conn.createStatement();
//5.执行sql语句
int count = stmt.executeUpdate(sql);
//6.处理结果
System.out.println(count);
catch (ClassNotFoundException | SQLException e)
e.printStackTrace();
finally
//7.关闭资源
if(stmt != null)//防止空指针异常
try
stmt.close();
catch (SQLException throwables)
throwables.printStackTrace();
if(conn != null)
try
conn.close();
catch (SQLException throwables)
throwables.printStackTrace();
@Test
public void testUpdate()
Statement stmt = null;
Connection conn = null;
try
//1.导入驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db2", "root", "root123");
//3.定义sql语句
String sql = "update account set balance='1000' where id=3";
//4.定义执行sql的对象
stmt = conn.createStatement();
//5.执行sql语句
int count = stmt.executeUpdate(sql);
//6.处理结果
System.out.println(count);
catch (ClassNotFoundException | SQLException e)
e.printStackTrace();
finally
//7.关闭资源
if(stmt != null)//防止空指针异常
try
stmt.close();
catch (SQLException throwables)
throwables.printStackTrace();
if(conn != null)
try
conn.close();
catch (SQLException throwables)
throwables.printStackTrace();
@Test
public void testDelete()
Statement stmt = null;
Connection conn = null;
try
//1.导入驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db2", "root", "root123");
//3.定义sql语句
String sql = "delete from account where id = 4";
//4.定义执行sql的对象
stmt = conn.createStatement();
//5.执行sql语句
int count = stmt.executeUpdate(sql);
//6.处理结果
System.out.println(count);
catch (ClassNotFoundException | SQLException e)
e.printStackTrace();
finally
//7.关闭资源
if(stmt != null)//防止空指针异常
try
stmt.close();
catch (SQLException throwables)
throwables.printStackTrace();
if(conn != null)
try
conn.close();
catch (SQLException throwables)
throwables.printStackTrace();
3.4 ResultSet:结果集对象,封装查询结果
-
boolean next(): 游标向下移动一行,判断当前行是否是最后一行末尾(是否有数据),如果是,则返回false,如果不是则返回true
-
getXxx(参数):获取数据
-
Xxx:代表数据类型 如: int getInt() , String getString()
-
参数:
- int:代表列的编号,从1开始 如: getString(1)
- String:代表列名称。 如: getDouble(“balance”)
- 注意:
- 使用步骤:
- 游标向下移动一行
- 判断是否有数据
- 获取数据
- 使用步骤:
-
-
练习:
- 定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回。
- 定义Emp类
- 定义方法 public List findAll()
- 实现方法 select * from emp;
- 定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回。
create table emp(
id int primary key,
ename varchar(50),
job_id int,
mgr int,
joindate date,
salary decimal(7, 2),
bonus decimal(7, 2),
dept_id int,
);
INSERT INTO emp(id,ename,job_id,mgr,joindate,salary,bonus,dept_id) VALUES
(1001,'孙悟空',4,1004,'2000-12-17','8000.00',NULL,20),
(1002,'卢俊义',3,1006,'2001-02-20','16000.00','3000.00',30),
(1003,'林冲',3,1006,'2001-02-22','12500.00','5000.00',30),
(1004,'唐僧',2,1009,'2001-04-02','29750.00',NULL,20),
(1005,'李逵',4,1006,'2001-09-28','12500.00','14000.00',30),
(1006,'宋江',2,1009,'2001-05-01','28500.00',NULL,30),
(1007,'刘备',2,1009,'2001-09-01','24500.00',NULL,10),
(1008,'猪八戒',4,1004,'2007-04-19','30000.00',NULL,20),
(1009,'罗贯中',1,NULL,'2001-11-17','50000.00',NULL,10),
(1010,'吴用',3,1006,'2001-09-08','15000.00','0.00',30),
(1011,'沙僧',4,1004,'2007-05-23','11000.00',NULL,20),
(1012,'李逵',4,1006,'2001-12-03','9500.00',NULL,30),
(1013,'小白龙',4,1004,'2001-12-03','30000.00',NULL,20),
(1014,'关羽',4,1007,'2002-01-23','13000.00',NULL,10);
package com.weeks.domain;
import java.util.Date;
public class Emp
private Integer id;
private String name;
private Integer jobId;
private Integer manager;
private Date joinDate;
private double salary;
private double bonus;
private Integer deptId;
public Integer getId()
return id;
public void setId(Integer id)
this.id = id;
public String getName()
return name;
public void setName(String name)
this.name = name;
public Integer getJobId()
return jobId;
public void setJobId(Integer jobId)
this.jobId = jobId;
public Integer getManager()
return manager;
public void setManager(Integer manager)
this.manager = manager;
public Date getJoinDate()
return joinDate;
public void setJoinDate(Date joinDate)
this.joinDate = joinDate;
public double getSalary()
return salary;
public void setSalary(double salary)
this.salary = salary;
public double getBonus()
return bonus;
public void setBonus(double bonus)
this.bonus = bonus;
public Integer getDeptId()
return deptId;
public void setDeptId(Integer deptId)
this.deptId = deptId;
@Override
public String toString()
return "Emp" +
"id=" + id +
", name='" + name + '\\'' +
", jobId=" + jobId +
", manager=" + manager +
", joinDate=" + joinDate +
", salary=" + salary +
", bonus=" + bonus +
", deptId=" + deptId +
'';
package com.weeks.jdbc;
import com.weeks.domain.Emp;
import org.junit.Test;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* jdbc ResultSet测试
*/
public class JDBCDemo4
@Test
public void testResultSet()
ResultSet resultSet = null;
Statement stmt = null;
Connection conn = null;
try
//1.导入驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "root123");
//3.定义sql语句
String sql = "select * from emp";
//4.定义执行sql的对象
stmt = conn.createStatement();
//5.执行sql语句
resultSet = stmt.executeQuery(sql);
//6.处理结果
Emp emp = null;
List<Emp> emps = new ArrayList<>();
while(resultSet.next())
//获取数据数据
int id = resultSet.getInt("id");
String name = resultSet.getString("ename");
int jobId = resultSet.getInt("job_id");
int manager = resultSet.getInt("mgr");
Date joinDate = resultSet.getDate("joindate");
double salary = resultSet.getDouble("salary");
double bonus = resultSet.getDouble("bonus");
int deptId = resultSet.getInt("dept_id");
//创建emp对象并赋值
emp = new Emp();
emp.setId(id);
emp.setName(name);
emp.setJobId(jobId);
emp.setManager(manager);
emp.setJoinDate(joinDateJavaWeb之JDBC