JDBC是一个独立于特定数据库管理系统,通用的sql数据库存储和操作的公共接口(API)。
package com.atguigu.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
/*
* Jdbc快速入门
* */
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://localhost:3306/db3?serverTimezone=GMT%2B8","root","123456");
//4、定义sql语句
String sql = "update account set balance = 500 where id = 1";
//5、获取数据库对象Statement
Statement stmt = conn.createStatement();
//6、执行sql
int count = stmt.executeUpdate(sql);
//7、处理结果
System.out.println(count);
//8、释放资源
stmt.close();
conn.close();
}
}
1、DriverManager:驱动管理对象
2、Connection:数据库连接对象
3、Statement: 执行sql的对象
4、ResultSet: 结果集对象,封装查询结果
while (rs.next()){
//循环判断结果是否有下一行
//循环数据
int id = rs.getInt(1);
String name = rs.getString("ac_name");
double balance = rs.getDouble(3);
System.out.println(id + "---" + name + "---" + balance);
}
package com.atguigu.connection;
import com.atguigu.exe.Account;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/*
* 定义一个方法,查询Account表的数据并将其封装为对象,然后装载集合,返回
* */
public class JDBCDemo8 {
public static void main(String[] args) {
List<Account> list = new JDBCDemo8().findAll();
System.out.println(list);
System.out.println(list.size());
}
/*
* 查询所有Account对象
* */
public List<Account> findAll() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
List<Account> list = null;
try {
//1、注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2、获取连接
conn = DriverManager.getConnection("jdbc:mysql:///db3?serverTimezone=GMT%2B8", "root", "123456");
//3、定义sql
String sql = "select * from account";
//4、获取执行sql的对象
stmt = conn.createStatement();
//5、执行sql
rs = stmt.executeQuery(sql);
//6、遍历结果集,封装对象,装载集合
Account account = null;
list = new ArrayList<Account>();
while (rs.next()) {
//获取数据
int id = rs.getInt("id");
String ac_name = rs.getString("ac_name");
int balance = rs.getInt("balance");
//创建account对象,并赋值
account = new Account();
account.setId(id);
account.setAc_name(ac_name);
account.setBalance(balance);
//装载集合
list.add(account);
}
} 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;
}
}
5、PreparedStatement:执行sql的对象
目的:简化书写
分析:
代码实现1:
package com.atguigu.util;
import javax.annotation.processing.Filer;
import java.awt.*;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
/*
* 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("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");
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取连接
*
* @return 连接对象
*/
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
/**
* 释放资源
*
* @param stmt
* @param conn
*/
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();
}
}
}
/**
* 释放资源
*
* @param stmt
* @param conn
*/
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();
}
}
}
}
需求:
步骤:
CREATE TABLE USER(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(32),
PASSWORD VARCHAR(32)
);
INSERT INTO USER VALUES(NULL,'zhangsan','123');
INSERT INTO USER VALUES(NULL,'lisi','234');
SELECT * from USER;
package com.atguigu.connection;
/*
* * 练习:
* 需求:
* 1、键盘录入用户名密码
* 2、判断用户是否登录成功
* */
import com.atguigu.util.JDBCUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
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("success!");
//登录失败
} else {
System.out.println("fail!");
}
}
/**
* 登录方法
*/
public boolean login(String username, String password) {
if (username == null || password == null) {
return false;
}
//连接数据库判断是否登录成功
Connection conn = null;
Statement stmt = 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;
}
}
是一个集合,存放数据库连接的容器。当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完后,会将连接对象归还给容器
步骤:
1、导入jar包
2、定义properties配置文件:
定义工具类:
1、定义一个类 JDBCUtils
2、提供静态代码块加载配置文件,初始化连接池对象
3、提供方法
Spring的框架对JDBC的简单封装。提供了JDBCTemplate对象简化JDBC的开发
步骤:
基本入门程序:
package cn.itcust.datasource.jdbctemplate;
import cn.itcust.datasource.utils.JDBCUtils;
import org.springframework.jdbc.core.JdbcTemplate;
/*
* JdbcTemplate入门
*/
public class JdbcTemplateDemo1 {
public static void main(String[] args) {
//1、导入jar包
//2、创建template对象
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
//3、调用方法
String sql = "update account set balance = 5000 where id = ?";
int count = template.update(sql,3);
System.out.println(count);
}
}
练习:
演示代码:
package cn.itcust.datasource.jdbctemplate;
import cn.itcust.datasource.domain.Emp;
import cn.itcust.datasource.utils.JDBCUtils;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public class JdbcTemplateDemo2 {
//1、获取JdbcTemplate对象
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
/**
* 修改一号数据的balance为10000
*/
@Test
public void test1() {
//2、定义sql
String sql = "update account set balance = 10000 where id = 1";
//3、执行sql
int count = template.update(sql);
System.out.println(count);
}
/**
* 添加已一条记录
*/
@Test
public void test2() {
String sql = "insert into account(id,ac_name,balance) value(?,?,?)";
int count = template.update(sql, 8, "老八", 5000);
System.out.println(count);
}
/**
* 删除刚刚添加的记录
*/
@Test
public void test3() {
String sql = "delete from account where id = ?";
int count = template.update(sql, 8);
System.out.println(count);
}
/**
* 查询id为1的记录,将其封装成集合map
* 注意:这个方法查询的结果集长度只能是1
*/
@Test
public void test4() {
String sql = "select * from account where id = ?";
Map<String, Object> map = template.queryForMap(sql, 1);
System.out.println(map);
//结果:{id=1, ac_name=zhangsan, balance=10000}
}
/**
* 查询所有记录,将其封装为Emp对象的list集合
*/
@Test
public void test5() {
String sql = "select * from account";
List<Map<String, Object>> list = template.queryForList(sql);
for (Map<String, Object> stringObjectMap : list) {
System.out.println(stringObjectMap);
}
}
/**
* 查询所有记录,将其封装为Emp对象的list集合
*/
@Test
public void test6() {
String sql = "select * from account";
List<Emp> list = template.query(sql, new RowMapper<Emp>() {
@Override
public Emp mapRow(ResultSet rs, int i) throws SQLException {
Emp emp = new Emp();
int id = rs.getInt("id");
String ac_name = rs.getString("ac_name");
int balance = rs.getInt("balance");
emp.setId(id);
emp.setAc_name(ac_name);
emp.setBalance(balance);
return emp;
}
});
for (Emp emp : list) {
System.out.println(emp);
}
}
/**
* 查询所有记录,将其封装为Emp对象的list集合
*/
@Test
public void test6_2() {
String sql = "select * from account";
List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
for (Emp emp : list) {
System.out.println(emp);
}
}
/**
* 查询所有记录数
*/
@Test
public void test7(){
String sql = "select count(id) from account";
Long total = template.queryForObject(sql,long.class);
System.out.println(total);
}
}