JDBC(Java Database connectivity)是一种执行SQL语句的Java API
可以为多种关系数据库提供统一访问
Java数据库连接规范(即一套接口)
JDBC四个核心类:
DriverManager 创建连接
Connection 连接类
Statement 用来执行sql语句
ResultSet 结果集
JDBC连接步骤:
1.注册驱动
2.获取连接 Connection
3.获取sql语句的执行对象 Statement
4.执行sql语句 返回结果集 ResultSet
5.处理结果集
6.关闭资源
// 1.注册驱动
/* 这种注册方式 相当于注册了两遍
Driver类内部的静态代码块已经注册了一遍
DriverManager.registerDriver(new Driver());
*/
// 直接把该类加载到内存当中 参数是全限定类名 (包名+类名)
Class.forName("com.mysql.jdbc.Driver");
// 2.获取连接对象
// url是访问数据库连接地址
String url = "jdbc:mysql://localhost:3306/myjdbc";
// 获取连接的方式一
Connection connection = DriverManager.getConnection(url, "root", "123456");
// 获取连接的方式二
Properties info = new Properties();
// 添加用户名 密码
info.setProperty("user", "root");
info.setProperty("password", "123456");
Connection connection = DriverManager.getConnection(url, info);
// 获取连接的方式三 相当于使用了一个get请求
// 携带参数 访问连接
String url2 = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
Connection connection = DriverManager.getConnection(url2);
// 3.获取执行sql语句的对象 Statement
Statement statement = connection.createStatement();
// 4.执行sql语句 返回结果集
String sql = "select * from users";
ResultSet resultSet = statement.executeQuery(sql);
// 5.处理结果集
// 循环遍历结果集输出结果
// 有记录next()方法返回true 反之false
while (resultSet.next()) {
// 打印数据
// 注意:查询数据库时 索引从1开始
// 结果集中添加的索引要和查询语句中的字段对应
System.out.println(resultSet.getObject(1));
System.out.println(resultSet.getObject(2));
System.out.println(resultSet.getObject(3));
System.out.println(resultSet.getObject(4));
System.out.println(resultSet.getObject(5));
}
// 6.关闭资源
resultSet.close();
statement.close();
connection.close();
@Test注解用来测试方法
注意:要使用public修饰的、无返回值的方法
// 插入方法
@Test
public void testInsert() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc";
Connection connection = DriverManager.getConnection(url, "root", "123456");
Statement statement = connection.createStatement();
String sql = "insert into users values(5,'ab','123','[email protected]','1997-06-23')";
// executeUpdate 增删改
// row 表示受影响的行数
int row = statement.executeUpdate(sql);
if (row>0) {
System.out.println("成功插入"+ row +"行");
}
connection.close();
statement.close();
}
// 更新方法
@Test
public void testUpdate() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc";
Connection connection = DriverManager.getConnection(url, "root", "123456");
Statement statement = connection.createStatement();
String sql = "update users set name='ac' where name='ab'";
int row = statement.executeUpdate(sql);
if (row>0) {
System.out.println("成功更新"+ row +"行");
}
connection.close();
statement.close();
}
// 删除方法
@Test
public void testDelete() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc";
Connection connection = DriverManager.getConnection(url, "root", "123456");
Statement statement = connection.createStatement();
String sql = "delete from users where id=5";
// 增删改
int row = statement.executeUpdate(sql);
if (row >0) {
System.out.println("成功删除"+ row +"行");
}
connection.close();
statement.close();
}
// 查询方法
@Test
public void testSelect() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc";
Connection connection = DriverManager.getConnection(url, "root", "123456");
Statement statement = connection.createStatement();
// 查询
String sql = "select id,name,email from users";
ResultSet resultSet = statement.executeQuery(sql);
// 处理结果集
while (resultSet.next()) {
// 可以直接填字段名称
System.out.println(resultSet.getObject("id"));
System.out.println(resultSet.getObject("name"));
System.out.println(resultSet.getObject("email"));
}
resultSet.close();
connection.close();
statement.close();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc", "root", "123456");
statement = connection.createStatement();
String sql = "select * from users";
resultSet = statement.executeQuery(sql);
// 处理结果集(把数据库的记录封装到对象中)
// 把对象保存到集合当中
ArrayList list = new ArrayList<>();
while (resultSet.next()) {
// 创建user对象
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
user.setBirthday(resultSet.getDate("birthday"));
// 放入集合中
list.add(user);
}
// 遍历打印
for (User user : list) {
System.out.println(user);
}
} catch (ClassNotFoundException e) {
// 停止程序
throw new RuntimeException("驱动加载失败");
} catch (SQLException e) {
throw new RuntimeException("获取连接失败");
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException("关闭失败");
}
// 加快系统回收的速度
resultSet = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
throw new RuntimeException("关闭失败");
}
statement = null;
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException("关闭失败");
}
connection = null;
}
}
JDBCUtil工具类
public class JDBCUtil {
private static String driverClass;
private static String url;
private static String user;
private static String password;
// 使用静态代码块加载驱动、读取配置文件(让驱动类只加载一次)
static {
// 使用系统类来读取配置文件
ResourceBundle rb = ResourceBundle.getBundle("dbinfo");
// 获取文件中的数据
driverClass = rb.getString("driverClass");
url = rb.getString("url");
user = rb.getString("user");
password = rb.getString("password");
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
/*
// 利用集合 读取文件
Properties properties = new Properties();
try {
FileInputStream fis = new FileInputStream("src/dbinfo.properties");
properties.load(fis);
// 读取文件
driverClass = properties.getProperty("driverClass");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
} catch (Exception e) {
}
*/
}
// 获取数据库连接的方法
public static Connection getConnection() throws ClassNotFoundException, SQLException {
return DriverManager.getConnection(url, user, password);
}
// 关闭数据库的方法 如果没有结果集需要关闭 直接传null
public static void closeAll(ResultSet resultSet, Statement statement, Connection connection) {
// 关闭资源前进行非空判断防止空指针出现
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException("关闭失败");
}
// 加快系统回收的速度
resultSet = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
throw new RuntimeException("关闭失败");
}
statement = null;
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException("关闭失败");
}
connection = null;
}
}
}
TestJDBCUtil测试类
public class TestJDBCUtil {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
@Test
public void testSelect() {
try {
// 获取连接
connection = JDBCUtil.getConnection();
statement = connection.createStatement();
String sql = "select * from users";
resultSet = statement.executeQuery(sql);
ArrayList<User> list = new ArrayList<>();
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
user.setBirthday(resultSet.getDate("birthday"));
list.add(user);
}
for (User user : list) {
System.out.println(user);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
JDBCUtil.closeAll(resultSet, statement, connection);
}
}
}
用户登录
public class Login {
public static void main(String[] args) {
// 接收用户输入的账号和密码
System.out.println("请输入账号:");
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
System.out.println("请输入密码:");
String password = scanner.nextLine();
// 调用查询方法
DoLogin dl = new DoLogin();
User user = dl.findUser(name, password);
if (user != null) {
System.out.println(user.getName()+"登录成功");
} else {
System.out.println("登录失败");
}
}
}
处理登录的查询操作
public class DoLogin {
public User findUser(String name,String password) {
User user = null;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
String sql = "select * from users where name='"+name+"' and password='"+password+"'";
// 查询数据库
try {
connection = JDBCUtil.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
user.setBirthday(resultSet.getDate("birthday"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(resultSet, statement, connection);
}
return user;
}
}
public class DoLogin {
public User findUser(String name,String password) {
User user = null;
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
// 占位符
String sql = "select * from users where name=? and password=?";
// 查询数据库
try {
connection = JDBCUtil.getConnection();
// 对sql语句进行预编译
statement = connection.prepareStatement(sql);
// 给sql语句的占位符 进行赋值
// 参数1 填索引 sql语句中问号索引
statement.setString(1, name);
statement.setString(2, password);
resultSet = statement.executeQuery();
if (resultSet.next()) {
user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
user.setBirthday(resultSet.getDate("birthday"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(resultSet, statement, connection);
}
return user;
}