public class JdbcDemo1 {
public static void main(String[] args) throws Exception {
//1. 导入驱动jar包
//2. 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//3. 获取数据库的连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql:///qzq?serverTimezone=GMT","root","");
//4. 定义SQL语句
String sql = "update account set balance = 500 where id = 1";
//5. 获取执行SQL语句的对象
Statement stmt = conn.createStatement();
//6. 执行SQL,接受返回结果
int count = stmt.executeUpdate(sql);
//7. 处理结果
System.out.println(count);
//8. 释放资源
stmt.close();
conn.close();
}
}
是一个类。
功能:
1. 注册驱动:告诉程序该使用哪一个数据库驱动jar包
static void registerDriver (Driver driver) :注册与给定的驱动程序 DriverManager 。
写代码使用:Class.forName("com.mysql.cj.jdbc.Driver");
通过查看源码发现:在com.mysql.cj.jdbc.Driver类中存在静态代码块
static{
try{
java.sql.DriverManager.registerDriver(new Driver());
}
catch (SQLException E){
throw new RuntimeException("Can't register driver!");
}
}
注意:MySQL5以后的驱动jar包可以省略注册驱动的步骤。
2. 获取数据库连接:
方法:static Connection getConnection(string url, string user, String password)
参数:
url:指定连接的路径
语法:jdbc:mysql://ip地址(域名):端口号/数据库名称
例子:jdbc:mysql://localhost:3306/qzq
细节:如果连接的是本机mysql服务器,并且服务默认端口是3306,则url可以简写为jdbc:mysql:///数据库名称
user:用户名
password:密码
功能:
1. 获取执行sql的对象
Statement createStatement()
PreparedStatement prepareStatement(String sql)
2. 管理事务:
开启事务:setAutoCommit(boolean autoCommit):调用该方法设置参数为false,即开启事务
提交事务:commit()
回滚事物:rollback()
执行sql:
1. boolean execute(String sql):可以执行任意的sql(了解)
2. int executeUpdate(String sql):执行DML(insert,update,delete)语句,DDL(create,alter,drop)语句
返回值:影响的行数,可以通过影响的行数判断DML语句是否执行成功,返回值>0的则执行成功,反之则失败。
3. ResultSet executeQuery(String sql):执行DQL(select)语句
练习:
/**
* account表 添加一条记录 insert 语句
* */
public class JdbcDemo2 {
public static void main(String[] args) {
Statement stmt=null;
Connection conn=null;
try {
//1. 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2. 定义sql
String sql = "insert into account values(null,'王五',3000)";
//3. 获取Connnection对象
conn = DriverManager.getConnection("jdbc:mysql:///qzq?serverTimezone=GMT","root","");
//获取执行sql的对象
stmt = conn.createStatement();
//5. 执行sql
int count = stmt.executeUpdate(sql);
//6. 处理结果
System.out.println(count);
if (count > 0){
System.out.println("添加成功!");
}
else {
System.out.println("添加失败!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//7. 释放资源
//避免空指针异常 stmt.close();
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//conn.close();
}
}
}
/**
* account表 修改记录
*/
public class JdbcDemo3 {
public static void main(String[] args) {
Statement stmt=null;
Connection conn=null;
try {
//1. 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2. 获取Connnection对象
conn = DriverManager.getConnection("jdbc:mysql:///qzq?serverTimezone=GMT","root","");
//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);
if (count > 0){
System.out.println("修改成功!");
}
else {
System.out.println("修改失败!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//7. 释放资源
//避免空指针异常 stmt.close();
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//conn.close();
}
}
}
/**
* account表 删除一条记录
*/
public class JdbcDemo4 {
public static void main(String[] args) {
Statement stmt=null;
Connection conn=null;
try {
//1. 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2. 获取Connnection对象
conn = DriverManager.getConnection("jdbc:mysql:///qzq?serverTimezone=GMT","root","");
//3. 定义sql
String sql="delete from account where id = 3";
//4. 获取执行sql的对象
stmt = conn.createStatement();
//5. 执行sql
int count = stmt.executeUpdate(sql);
//6. 处理结果
System.out.println(count);
if (count > 0){
System.out.println("删除成功!");
}
else {
System.out.println("删除失败!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//7. 释放资源
//避免空指针异常 stmt.close();
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//conn.close();
}
}
}
/**
* 执行DDL
*/
public class JbdcDemo5 {
public static void main(String[] args) {
Statement stmt=null;
Connection conn=null;
try {
//1. 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2. 获取Connnection对象
conn = DriverManager.getConnection("jdbc:mysql:///qzq?serverTimezone=GMT","root","");
//3. 定义sql
String sql="create table student (id int,name varchar(20))";
//4. 获取执行sql的对象
stmt = conn.createStatement();
//5. 执行sql
int count = stmt.executeUpdate(sql);
//6. 处理结果
System.out.println(count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//7. 释放资源
//避免空指针异常 stmt.close();
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//conn.close();
}
}
}
next():将光标从当前位置向前移一行。
getXxx(参数):获取数据(一次获取某一行某一列的数据)
Xxx:代表数据类型 如:int getInt() string getString()
参数:代表列的名称。
public class JdbcDemo6 {
public static void main(String[] args) {
Statement stmt=null;
Connection conn=null;
ResultSet rs=null;
try {
//1. 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2. 获取Connnection对象
conn = DriverManager.getConnection("jdbc:mysql:///qzq?serverTimezone=GMT","root","");
//3. 定义sql
String sql="select * from account";
//4. 获取执行sql的对象
stmt = conn.createStatement();
//5. 执行sql
rs = stmt.executeQuery(sql);
//6. 处理结果
//6.1 让游标向下移动一行
rs.next();
//6.2 获取数据
int id = rs.getInt(1);
String name = rs.getNString("name");
double balance = rs.getDouble("balance");
System.out.println(id + "---" + name + "---" + balance);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//7. 释放资源
//避免空指针异常
if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//stmt.close();
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//conn.close();
}
}
}
注意:
使用步骤:
// 循环判断游标是否在最后一行末尾
while(rs.next()){
//获取数据
int id = rs.getInt(1);
String name = rs.getNString("name");
double balance = rs.getDouble("balance");
System.out.println(id + "---" + name + "---" + balance);
}
练习:
定义一个方法,查询employee表的数据,将其封装为对象,然后装载集合,返回。
1. 定义Employee类
2. 定义方法 public List findAll(){}
3. 实现方法 select * from employee;
代码实现:
/**
* 封装Employee表数据的JavaBean
*/
public class Employee {
private int id;
private String name;
private int age;
private int dep_id;
private Date join_date;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getDep_id() {
return dep_id;
}
public void setDep_id(int dep_id) {
this.dep_id = dep_id;
}
public Date getJoin_date() {
return join_date;
}
public void setJoin_date(Date join_date) {
this.join_date = join_date;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", dep_id=" + dep_id +
", join_date=" + join_date +
'}';
}
}
/**
* 定义一个方法,查询employee表的数据,将其封装为对象,然后装载集合,返回。
*/
public class JdbcDemo8 {
public static void main(String[] args) {
List list = new JdbcDemo8().findAll();
System.out.println(list);
}
/**
* 查询所有Employee对象
*/
public List findAll(){
Statement stmt=null;
Connection conn=null;
ResultSet rs=null;
List list=null;
try {
//1. 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2. 获取Connnection对象
conn = DriverManager.getConnection("jdbc:mysql:///ycy?serverTimezone=GMT","root","");
//3. 定义sql
String sql="select * from employee";
//4. 获取执行sql的对象
stmt = conn.createStatement();
//5. 执行sql
rs = stmt.executeQuery(sql);
//6. 遍历结果集,封装对象,装载集合
Employee employee = null;
list=new ArrayList();
while(rs.next()){
//获取数据
int id = rs.getInt("id");
String name = rs.getNString("NAME");
int age = rs.getInt("age");
int dep_id = rs.getInt("dep_id");
Date join_date = rs.getDate("join_date");
//创建employee对象,并赋值
employee=new Employee();
employee.setId(id);
employee.setName(name);
employee.setAge(age);
employee.setDep_id(dep_id);
employee.setJoin_date(join_date);
//装载集合
list.add(employee);
}
}catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}finally {
if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
}
/**
* 登录方法,使用PrepareStatement
*/
public boolean login2(String username,String password){
if (username == null || password == null){
return false;
}
//连接数据库判断是否登录成功
PreparedStatement pstmt=null;
Connection conn=null;
ResultSet rs=null;
//1. 获取连接
try {
conn = JdbcUtils.getConnection();
//2. 定义sql
String sql = "select * from USER where username = ? and password = ?";
//3. 获取执行sql的对象
pstmt = conn.prepareStatement(sql);
//给?赋值
pstmt.setString(1,username);
pstmt.setString(2,password);
//4. 执行查询,不需要传递sql
rs = pstmt.executeQuery();
//5. 判断
return rs.next();//如果有下一行则返回true
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.close(rs,pstmt,conn);
}
return false;
}
我们发现每一次写的代码重复度都很高,所以想要用一个工具类来简化它
目的:简化书写
分析:
1. 注册驱动也抽取
2. 抽取一个方法获取连接对象
需求:不想传递参数(麻烦),还得保证工具类的通用性。
解决:配置文件
jdbc.properties
url=
user=
password=
3. 抽取一个方法来释放资源
代码实现:
url=jdbc:mysql:///ycy
user=root
password=
driver=com.mysql.cj.jdbc.Driver
/**
* JDBC工具类
*/
public class JdbcUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
/**
* 文件的读取只需要读取一次即可拿到这些值,使用静态代码块
*/
static {
//读取资源文件,获取值。
try {
//1. 创建Properties集合类。
Properties pro=new Properties();
//获取src路径下文件的方式--->Classloader 类加载器,可以加载字节码文件进内存
ClassLoader classLoader = JdbcUtils.class.getClassLoader();
URL res = classLoader.getResource("jdbc.properties");
String path = res.getPath();
System.out.println(path);
//2. 加载文件
//pro.load(new FileReader("C:\\Users\\lennovo\\Desktop\\jdbc\\day04_jdbc\\src\\jdbc.properties"));
pro.load(new FileReader(path));
//3. 获取数据属性
url=pro.getProperty("url");
user=pro.getProperty("user");
password=pro.getProperty("password");
driver=pro.getProperty("driver");
//4. 注册驱动
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取连接
* 连接对象
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
/**
* 释放资源
*/
public static void close(Statement stmt,Connection conn){
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs, Statement stmt, Connection conn){
if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/**
* 演示JDBC工具类
*/
public class JdbcDemo8 {
public static void main(String[] args) {
List list = new JdbcDemo8().findAll2();
System.out.println(list);
}
public List findAll2(){
Statement stmt=null;
Connection conn=null;
ResultSet rs=null;
List list=null;
try {
/* //1. 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2. 获取Connnection对象
conn = DriverManager.getConnection("jdbc:mysql:///ycy?serverTimezone=GMT","root","");
*/
conn=JdbcUtils.getConnection();
//3. 定义sql
String sql="select * from employee";
//4. 获取执行sql的对象
stmt = conn.createStatement();
//5. 执行sql
rs = stmt.executeQuery(sql);
//6. 遍历结果集,封装对象,装载集合
Employee employee = null;
list=new ArrayList();
while(rs.next()){
//获取数据
int id = rs.getInt("id");
String name = rs.getNString("NAME");
int age = rs.getInt("age");
int dep_id = rs.getInt("dep_id");
Date join_date = rs.getDate("join_date");
//创建employee对象,并赋值
employee=new Employee();
employee.setId(id);
employee.setName(name);
employee.setAge(age);
employee.setDep_id(dep_id);
employee.setJoin_date(join_date);
//装载集合
list.add(employee);
}
}catch (SQLException e) {
e.printStackTrace();
}finally {
/*if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}*/
JdbcUtils.close(rs,stmt,conn);
}
return list;
}
}
练习:
需求:
1. 通过键盘录入用户名和密码
2. 判断用户是否登录成功
select * from user where username = “” and password = “”;
如果这个sql有查询结果,则成功,反之,则失败
步骤:
1. 创建数据库表 user
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32),
PASSWORD VARCHAR(32)
);
INSERT INTO USER VALUES(NULL,'zhangsan','123');
INSERT INTO USER VALUES(NULL,'lisi','234');
public class JdbcDemo9 {
public static void main(String[] args) {
//1. 键盘录入,接收用户名和密码
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
//2. 调用方法
boolean flag = new JdbcDemo9().login(username,password);
//3. 判断结果,输出不同语句
if (flag){
//登录成功
System.out.println("登录成功");
}else {
System.out.println("登录失败");
}
}
/**
* 登录方法
*/
public boolean login(String username,String password){
if (username == null || password == null){
return false;
}
//连接数据库判断是否登录成功
Statement stmt=null;
Connection conn=null;
ResultSet rs=null;
//1. 获取连接
try {
conn = JdbcUtils.getConnection();
//2. 定义sql
String sql = "select * from USER where username = '"+username+"' and password = '"+password+"'";
//3. 获取执行sql的对象
stmt = conn.createStatement();
//4. 执行查询
rs = stmt.executeQuery(sql);
//5. 判断
return rs.next();//如果有下一行则返回true
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.close(rs,stmt,conn);
}
return false;
}
}