当前位置: 首页 > news >正文

[ JDBC ] java 数据库连接

目录

1. 定义:

2. JDBC API----供程序员调用的接口与类( java.sql 包中)

3. JDBC搭建

    1. 建立与数据库的链接

    2. 执行SQL语句

      (1)Satement执行sql语句

      (2)PrepareStatement执行sql语句

      (3)Satement和PrepareStatement 安全性比较

    3. 关闭与数据库的各种连接

4.结果集处理

  (1)查询返回单个对象

  (2)查询返回多个对象


1. 定义:

        JDBC(Java DataBase Connectivity) java数据库连接: 是一种用于执行SQL语句的Java API,为多种关系型数据库提供了统一访问,由一组(Java语言编写的)类和接口组成,提供了增 删 改 查 等方法来更新数据库中数据

注意 : Java开发者只制定JDBC规范,不同数据库开发商对接口进行实现 , 程序员学习如何使用规范

2. JDBC API----供程序员调用的接口与类( java.sql 包中)

    (1)DriverManager类作用:管理各种不同的jDBC驱动

    (2)Connection 接口 与特定数据库的连接

    (3)Statement 接口 执行sql

    (4)PreparedStatement接口 执行sql

    (5)ResultSet接口 接收查询结果

3. JDBC搭建

      注意前提: 导入mysql的jar包

package ffyc.jdbc.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;public class Demo1 {public static void main(String[] args) {String name = "C++";//1. 建立与数据库的链接String url = "jdbc:mysql://127.0.0.1:3306/schooldb?serverTimezone=Asia/Shanghai";//数据库地址String user = "root";//数据库用户名String dbpwd = "root";//数据库密码try {//建立与数据库的链接通道,返回一个链接对象  Connection对象表示一个与数据库的通道Connection connection = DriverManager.getConnection(url,user,dbpwd);// System.out.println(connection);com.mysql.cj.jdbc.ConnectionImpl@37574691//2.发送sqlStatement statement = connection.createStatement();// System.out.println(statement);com.mysql.cj.jdbc.StatementImpl@71248c21int row =  statement.executeUpdate("insert into course(name)value('"+name+"')");//执行新增修改删除 发送sql到数据库System.out.println(row);//3.关闭与数据库的各种链接statement.close();connection.close();} catch (SQLException e) {System.out.println("数据库连接失败");e.printStackTrace();}}
}

    1. 建立与数据库的链接

使用DriverManager.getConnection()方法创建Connection对象,表示一个物理连接的数据库

Connection conn = DriverManager.getConnection(url,user,pass);

url: jdbc:mysql://ip:端口(3306)/数据库名?serverTimezone=Asia/Shanghai   (固定格式)

user: 用户名(root)

pass: 密码

 注意: 可以创建一个JDBCUtil类 封装"与数据库连接"的代码,在使用时直接调用即可,减少代码冗余

package ffyc.jdbc.demo;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
//将连接数据库的方法定义成一个类,使用的时候直接调用
public class JDBCUtil {//将数据库的地址 用户名 密码定义为 私有静态的 不需要被外界访问且只加载一次private static String url = "jdbc:mysql://127.0.0.1:3306/schooldb?serverTimezone=Asia/Shanghai";//数据库地址private static String user = "root";//数据库用户名private static String dbpwd = "root";//数据库密码public static Connection getConnection() throws SQLException {Connection connection = DriverManager.getConnection(url,user,dbpwd);return  connection;}
}

    2. 执行SQL语句

       (1)Satement执行sql语句
package ffyc.jdbc.demo;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;public class Demo2 {public static void main(String[] args) {try {//Demo2.add(107,"赵六","男","161613");//Demo2.update(5,110,"赵四","女","151515");Demo2.delete(5);} catch (SQLException e) {e.printStackTrace();//打印异常信息System.out.println("数据库操作失败");}}//添加学生public static void add(int num,String name ,String gender ,String phone) throws SQLException {//增加Connection connection = JDBCUtil.getConnection();//获得数据库连接的对象 相当于建立connection通道Statement statement = connection.createStatement();//执行静态SQL语句 相当于将SQL封装在Statement里面,再借助通道connection通道,发送给数据库//执行(execute)数据: 数值类型双引双加  字符串类型先单引再双引双加statement.executeUpdate("insert into student(num,name,gender,phone,regtime)value("+num+",'"+name+"','"+gender+"','"+phone+"',now())");//关闭与数据库的连接statement.close();connection.close();}//修改学生public static void update(int id ,int num,String name,String gender,String phone) throws SQLException {Connection connection = JDBCUtil.getConnection();//通道Statement statement =connection.createStatement();//封装statement.executeUpdate("update student set num="+num+",name='"+name+"',gender='"+gender+"',phone='"+phone+"'where id ="+id);//关闭与数据库的连接statement.close();connection.close();}//删除学生public static void delete(int id) throws SQLException {Connection connection =  JDBCUtil.getConnection();//通道Statement statement = connection.createStatement();//封装statement.executeUpdate("delete from student where id ="+id);//关闭与数据库的连接statement.close();connection.close();}
}

  ResultSet executeQuery(String sql); 用于执行查询语句,返回一个ResultSet 集合

   (2)PrepareStatement执行sql语句
package ffyc.jdbc.demo;import com.mysql.cj.x.protobuf.MysqlxPrepare;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;public class Demo3 {public static void main(String[] args) {try {//Demo3.add(107,"赵四","女","1212124");//Demo3.update(6,110,"赵六","女","161613");Demo3.delete(6);} catch (SQLException e) {e.printStackTrace();}}//添加学生public static void add(int num,String name ,String gender ,String phone) throws SQLException {//增加Connection connection = JDBCUtil.getConnection();//获得数据库连接对象 connection相当于建立通道PreparedStatement ps = connection.prepareStatement("insert into student (num,name,gender,phone,regtime)value(?,?,?,?,now())");//预编译的SQL语句ps.setObject(1,num);////按顺序向SQL的占位符填充数据 1---第一个问号对应的数据                                                   //?是占位符,表示此处需要传递一个值ps.setObject(2,name);ps.setObject(3,gender);ps.setObject(4,phone);//相当于组装数据,但是不执行ps.executeUpdate();//执行SQLps.close();//关闭与数据库的连接connection.close();}public static void update(int id ,int num,String name,String gender,String phone) throws SQLException {//修改Connection connection = JDBCUtil.getConnection();PreparedStatement ps =connection.prepareStatement("update student set num=?,name=?,gender=?,phone=? where id = ?");ps.setObject(1,num);ps.setObject(2,name);ps.setObject(3,gender);ps.setObject(4,phone);ps.setObject(5,id);ps.executeUpdate();//执行SQLps.close();//关闭与数据库的连接connection.close();}public static void delete(int id) throws SQLException {Connection connection = JDBCUtil.getConnection();PreparedStatement ps =connection.prepareStatement("delete from student where id =?");ps.setObject(1,id);ps.executeUpdate();//执行SQLps.close();//关闭与数据库的连接connection.close();}
}

  ResultSet executeQuery(); 用于执行查询语句 返回一个ResultSet 集合

      (3)Satement和PrepareStatement 安全性比较

         使用预编译PrepareStatement语句.传入任何内容都不会和原语句(100 or 1=1)发生任何匹配的关系. 预编译模式中每个占位符处,只能插入一个值,而会过滤其他语句

package ffyc.jdbc.demo;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;public class Demo4 {public static void main(String[] args) throws SQLException {Demo4.delete("100 or 1=1");}//安全性比较public static void delete(String id) throws SQLException {//Statement 安全性较低, 不能方式SQL注入Connection connection = JDBCUtil.getConnection();Statement statement = connection.createStatement();statement.executeUpdate("delete from student where id = "+id);statement.close();connection.close();/* PreparedStatement安全性较高 因为一个?只能占一个位 可以防止SQL注入,被恶意攻击Connection connection = JDBCUtil.getConnection();PreparedStatement ps = connection.prepareStatement("delete from student where id = ?");ps.setObject(1, id);ps.executeUpdate();ps.close();connection.close();*/}
}

    3. 关闭与数据库的各种连接

4.结果集处理

     PreparedStatement和Statement中的executeQuery()方法中会返回一个ResultSet对象,将查询结果封装在此对象中

  (1)查询返回单个对象

package ffyc.jdbc.demo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//查询返回单个对象
public class Demo5 {public static void main(String[] args) throws SQLException {//通过学生的ID,查询唯一的一个学生的信息,返回一个学生对象Student student = Demo5.findStudentById(10);System.out.println(student);System.out.println(student);}public static Student findStudentById(int id) throws SQLException {Connection connection = JDBCUtil.getConnection();//获得连接对象PreparedStatement ps = connection.prepareStatement("select id,num,name,gender,birthday,phone,regtime from student where id = ?");//封装ps.setObject(1,id);//executeQuery()查询执行后,将数据返回到一个ResultSet对象中ResultSet resultSet = ps.executeQuery();//由于resultSet中没有getid等方法直接使用,需要将ResultSet对象中的数据取出来,放到一个Student对象中,便于后续的使用Student student = new Student();while(resultSet.next()){//获得下一行数据,next()指向结果集中的数据student.setId(resultSet.getInt("id"));student.setNum(resultSet.getInt("num"));student.setName(resultSet.getString("name"));student.setGender(resultSet.getString("gender"));student.setPhone(resultSet.getString("phone"));student.setBirthday(resultSet.getDate("birthday"));//getDate() 获得年月日student.setRegTime(resultSet.getTimestamp("regtime"));//getTimestamp() 获得是年月日时分秒}resultSet.close();ps.close();connection.close();return student;}
}

   (2)查询返回多个对象

package ffyc.jdbc.demo;
import java.sql.*;
import java.util.ArrayList;
//查询返回多个对象
public class Demo6 {public static void main(String[] args) throws SQLException {ArrayList<Student> students = Demo6.findStudentByGender("男");System.out.println(students);}public static ArrayList<Student> findStudentByGender(String gender) throws SQLException {ArrayList<Student> students =new ArrayList<>();//封装查询到的多个对象Connection connection = JDBCUtil.getConnection();PreparedStatement ps =connection.prepareStatement("select id,num,name,gender,birthday,phone,regtime from student where gender = ?");ps.setObject(1,gender);ResultSet resultSet = ps.executeQuery();//包装while(resultSet.next()){Student student = new Student();//创建学生对象student.setId(resultSet.getInt("id"));student.setNum(resultSet.getInt("num"));student.setName(resultSet.getString("name"));student.setGender(resultSet.getString("gender"));student.setPhone(resultSet.getString("phone"));student.setBirthday(resultSet.getDate("birthday"));//getDate() 获得年月日student.setRegTime(resultSet.getTime("regtime"));//getTimestamp() 获得年月日时分秒students.add(student);//将所有学生对象都添加到集合里面}resultSet.close();ps.close();connection.close();return students;}
}

http://www.lryc.cn/news/616412.html

相关文章:

  • 应对高并发 - TCP/IP网络栈核心参数调优
  • (三)全栈(部署)
  • 滚动条开始滚动时,左侧导航固定,当左侧内容触底到footer时左侧内容取消固定并跟随滚动条滚动
  • Vue3入门到精通:2.4 Vue3动态组件与异步组件深度解析
  • 【Redis】持久化方案——RDB和AOF
  • RK3588在YOLO12(seg/pose/obb)推理任务中的加速方法
  • Kafka消费者相关原理
  • 纳维 - 斯托克斯方程的存在性与光滑性:流体世界的千年谜题
  • Python训练营打卡DAY 26 函数专题1:函数定义与参数
  • 大模型工具集成四层架构:识别、协议、执行与实现
  • JS中typeof与instanceof的区别
  • 专题三_二分_二分查找
  • 单片机捷径
  • Shell脚本-了解i++和++i
  • Linux常用命令(后端开发版)
  • NVIDIA Jetson AGX Orin 全景解析——边缘计算的高性能选择
  • 6A 工作流:让 Cursor、Trae 等AI编程助手按流程交付的实战手册
  • 机器学习——多元线性回归
  • React Profiler
  • HarmonyOS NEXT系列之编译三方C/C++库
  • 【Jenkins入门以及安装】
  • 《动手学深度学习》读书笔记—10.4 Bahdanau注意力
  • 移动端音频处理实践:59MB变声应用的技术实现分析
  • MySQL中的in和exists的区别
  • C++多线程服务器
  • Spring循环依赖详解
  • MySQL面试题及详细答案 155道(041-060)
  • LeeCode 46. 全排列
  • 冒泡排序实现以及优化
  • 20250810 | 深度学习入门笔记1