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

JDBC学习汇总

概念

JDBC:JDBC是Java提供的一套用来操作数据库的接口

通过Java代码操作数据库

1.确定数据库是可以正常使用(MySQL服务是否正常开启)

2.确定MySQL的账号和密码是正确的

3.确定MySQL版本和MySQL驱动版本匹配

4.在工程(module)上右键创建一个目录并将驱动包放在此目录中

5.在jar包上右键-->add as library

 获取Connection方式一

connect(String url,java.util.Properties info)
         url: mysql的连接地址
         jdbc:mysql://localhost:3306/atguigu
         jdbc:mysql:协议
        localhost:mysql服务器的地址
        3306:端口号
        atguigu:库的名字

  @Testpublic void test() throws SQLException {//1.创建Driver对象Driver driver = new com.mysql.jdbc.Driver();//全类名:包含包名在内的类的全名称//2.调用方法--获取Connection对象(有了该对象才能操作数据库)String s = "jdbc:mysql://localhost:3306/myemployees";Properties p = new Properties();p.setProperty("user","root");//账号,key不能随便写p.setProperty("password","123123");//密码,key不能随便写Connection connect = driver.connect(s,p);System.out.println(connect);}

Properties

1.Properties是Hashtable的子类

2.Properties中的key,value默认是String类型

3.常用Properties读取配置文件

//首先在项目中创建一个文件,文件名为jdbc.properties
//文件内容如下:
user=root
password=123321//程序如下:@Testpublic void test() throws IOException {//1.创建Properties对象Properties p = new Properties();//2.创建流FileInputStream fis = new FileInputStream("jdbc.properties");//3.加载流--将流加载到Properties中p.load(fis);//4.通过Properties读取文件中的内容String user = p.getProperty("user");String password = p.getProperty("password");System.out.println(user + "-----" + password);//5.关闭资源fis.close();}

获取Connection方式二:通过DriverManager

    @Testpublic void test2() throws SQLException {//1.创建Driver对象Driver driver = new com.mysql.jdbc.Driver();//2.将driver注册到DriverManager中DriverManager.registerDriver(driver);//获取Connection对象String url = "jdbc:mysql://localhost:3306/myemployees";Connection connection = DriverManager.getConnection(url,"root","123123");System.out.println(connection);}

方式二的优化

    @Testpublic void test3() throws ClassNotFoundException, SQLException {//1.让driver类中的静态代码块执行Class.forName("com.mysql.jdbc.Driver");//2.获取connection对象String url = "jdbc:mysql://localhost:3306/myemployees";Connection connection = DriverManager.getConnection(url,"root","123123");System.out.println(connection);}

获取Connection方式三(最终方式)

//首先在项目中创建一个文件,文件名为jdbc.properties
//文件内容如下:
user=root
password=123321//程序如下:@Testpublic void test4() throws ClassNotFoundException, SQLException, IOException {String className = "";String url = "";String user = "";String password = "";//读取配置文件//1.创建Properties对象Properties p = new Properties();//2.创建流FileInputStream fis = new FileInputStream("jdbc.properties");//3.加载流--将流加载到Properties中p.load(fis);//4.通过Properties读取文件中的内容user = p.getProperty("user");password = p.getProperty("password");url = p.getProperty("url");className = p.getProperty("className");System.out.println(user + "---" + password + "---" + url + "---" + className);//5.关闭资源fis.close();//1.让driver类中的静态代码块执行Class.forName(className);//2.获取connection对象Connection connection = DriverManager.getConnection(url,user,password);System.out.println(connection);}

JDBCUtils工具类

//首先在项目中创建一个文件,文件名为jdbc.properties
//文件内容如下:
user=root
password=123321
url=jdbc:mysql://localhost:3306/myemployees
className=com.mysql.jdbc.Driver//----------------------------------
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;/*
* 工具类
* */
public class JDBCUtils {private static String className;private static String url;private static String user;private static String password;static {FileInputStream fis = null;try {//读取配置文件//1.创建Properties对象Properties p = new Properties();//2.创建流fis = new FileInputStream("jdbc.properties");//3.加载流--将流加载到Properties中p.load(fis);//4.通过Properties读取文件中的内容user = p.getProperty("user");password = p.getProperty("password");url = p.getProperty("url");className = p.getProperty("className");System.out.println(user + "---" + password + "---" + url + "---" + className);}catch (Exception e){e.printStackTrace();//打印异常信息//将编译时异常转为运行时异常---终止程序的运行throw new RuntimeException(e.getMessage());//e.getMessage():获取异常信息}finally {if (fis != null) {//5.关闭资源try {fis.close();} catch (IOException e) {throw new RuntimeException(e);}}}}//获取Connection对象public static Connection getConnection(){try {//1.让driver类中的静态代码块执行Class.forName(className);//2.获取connection对象Connection connection = DriverManager.getConnection(url,user,password);
//        System.out.println(connection);return connection;}catch (Exception e){e.printStackTrace();throw new RuntimeException(e.getMessage());}}//关闭资源public static void close(Connection connection, PreparedStatement ps) {if (connection != null){try {connection.close();} catch (SQLException e) {e.printStackTrace();}}if (ps != null){try {ps.close();} catch (SQLException e) {e.printStackTrace();}}}
}

向表中插入数据

    @Testpublic void test() throws SQLException {//1.获取Connection对象Connection connection = JDBCUtils.getConnection();//2.sql语句//?:占位符String sql = "insert into student(id,name,sid) values(?,?,?)";//3.对SQL预编译//调用PrepareStatement返回PrepareStatement对象,有了该对象就可以给占位符赋值PreparedStatement ps = connection.prepareStatement(sql);//4.给占位符赋值/** setInt(int parameterIndex,int x)* parameterIndex:第几个占位符* */ps.setInt(1,10);ps.setString(2,"longge");ps.setInt(3,1000);//5.执行sql语句int result = ps.executeUpdate();//executeUpdate:只是用来执行增,删,改System.out.println("共有" + result + "行数据受到影响");//6.关闭资源JDBCUtils.close(connection,ps);}

更改表中数据

     /** 修改数据库中数据* */@Testpublic void test1() throws SQLException {//1.获取Connection对象Connection connection = JDBCUtils.getConnection();//2.sql语句String sql = "update student set id=? where name=?";//3.预编译PreparedStatement ps = connection.prepareStatement(sql);//3.1给占位符赋值ps.setInt(1,9);ps.setString(2,"longge");//3.2执行sql语句ps.executeUpdate();//4.关闭资源JDBCUtils.close(connection,ps);}

删除表中数据

    /** 删除数据库中数据* */@Testpublic void test2() throws SQLException {//1.获取Connection对象Connection connection = JDBCUtils.getConnection();//2.sql语句String sql = "delete from student where id = ?";//3.预编译PreparedStatement ps = connection.prepareStatement(sql);//3.1给占位符赋值ps.setInt(1,9);//3.2执行sql语句ps.executeUpdate();//4.关闭资源JDBCUtils.close(connection,ps);}

查询表中的一条数据

    /** 查询表中的一条数据* */@Testpublic void test() throws SQLException {//1.获取Connection对象Connection connection = JDBCUtils.getConnection();//2.sql语句String sql = "select id,name,sid from student where id = ?";//3.预编译PreparedStatement ps = connection.prepareStatement(sql);//4.给占位符赋值ps.setInt(1,3);//5.执行sql语句ResultSet rs = ps.executeQuery();//executeQuery():执行查询的语句//6.通过ResultSet遍历数据while (rs.next()){//next():如果有数据结果为true//7.获取对应的字段中的数据//getInt(String columnLabel):通过字段的名字获取对应的值int id = rs.getInt("id");String name = rs.getString("name");int sid = rs.getInt("sid");System.out.println(id + "=" + name + "=" + sid);}//8.关闭资源JDBCUtils.close(connection,ps,rs);}

查询表中所有数据(查询一条数据的修改式)

    /** 查询表中的所有数据* */@Testpublic void test2() throws SQLException {//1.获取Connection对象Connection connection = JDBCUtils.getConnection();//2.sql语句String sql = "select id,name,sid from student";//3.预编译PreparedStatement ps = connection.prepareStatement(sql);//5.执行sql语句ResultSet rs = ps.executeQuery();//executeQuery():执行查询的语句//6.通过ResultSet遍历数据while (rs.next()){//next():如果有数据结果为true//7.获取对应的字段中的数据//getInt(String columnLabel):通过字段的名字获取对应的值int id = rs.getInt("id");String name = rs.getString("name");int sid = rs.getInt("sid");System.out.println(id + "=" + name + "=" + sid);}//8.关闭资源JDBCUtils.close(connection,ps,rs);}

查询表中的所有数据(调用类的方法)

    @Testpublic void test3() throws SQLException {List<Student> students = getStudents();for (Student student : students) {System.out.println(student);}}/** 自定义一个方法。调用此方法就可以获取表中所有的数据* */public List<Student> getStudents() throws SQLException {//创建一个集合用来存放对象List<Student> list = new ArrayList<>();Connection connection = JDBCUtils.getConnection();String sql = "select id,name,sid from student";PreparedStatement ps = connection.prepareStatement(sql);ResultSet rs = ps.executeQuery();while (rs.next()){//next():如果有数据结果为trueint id = rs.getInt("id");String name = rs.getString("name");int sid = rs.getInt("sid");//封装Student s = new Student(id,name,sid);//将对象放入到集合中list.add(s);}//8.关闭资源JDBCUtils.close(connection,ps,rs);//返回集合return list;}

事务

import com.atguigu.jdbc2.JDBCUtils;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;/*#事务:#一组逻辑操作单元,使数据从一种状态变换到另一种状态#案例:# AA给CC转账1000元try{事务开启AA减去1000元的操作;System.out.println(1/0);CC加上1000元的操作;事务提交}catch(Exception e){事务回滚;}finally{允许事务提交}遇到的问题:可能会发生AA的操作成功但是CC的操作失败解决思路:将AA和CC的操作看成一个整体看成一个整体要么都成功要么都失败CREATE TABLE account(NAME VARCHAR(20),balance INT);
* */
public class Account {public static void main(String[] args) {//获取Connection对象Connection connection = JDBCUtils.getConnection();PreparedStatement ps = null;try {//============开启事务---禁止自动提交===============connection.setAutoCommit(false);//sql语句String sql = "update account set balance=? where name=?";//预编译ps = connection.prepareStatement(sql);//给占位符赋值//AA减去1000ps.setInt(1, 1000);ps.setString(2, "aa");//执行sql语句ps.executeUpdate();
//            System.out.println(1 / 0);//CC加上1000ps.setInt(1, 3000);ps.setString(2, "cc");//执行sql语句ps.executeUpdate();//=========事务---提交=====connection.commit();} catch (Exception e) {//======事务---回滚====try {connection.rollback();} catch (SQLException ex) {throw new RuntimeException(ex);}e.printStackTrace();} finally {//允许事务提交try {connection.commit();} catch (SQLException e) {e.printStackTrace();}//关闭资源JDBCUtils.close(connection, ps);}}
}

数据库连接池

package com.atguigu.jdbc3;import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.junit.jupiter.api.Test;import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;/*
* 数据库连接池:Druid
* */
public class DruidDemo {/** 方式一:* */@Testpublic void test() throws SQLException {//1.创建数据库连接池对象DruidDataSource dataSource = new DruidDataSource();//2.给属性赋值dataSource.setUsername("root");//mysql账号dataSource.setPassword("123123");//mysql密码dataSource.setDriverClassName("com.mysql.jdbc.Driver");//Driver类的全类名dataSource.setUrl("jdbc:mysql://localhost:3306/myemployees");//3.获取Connection对象Connection connection = dataSource.getConnection();System.out.println(connection);//4.关闭资源connection.close();}/** 方式二:* */@Testpublic void test2() throws Exception {Properties p = new Properties();FileInputStream fis = new FileInputStream("druid.properties");p.load(fis);//加载流//1.创建数据库的连接对象DataSource dataSource = DruidDataSourceFactory.createDataSource(p);//2.获取数据库连接对象Connection connection = dataSource.getConnection();System.out.println(connection);//3.关闭connection.close();}
}

不能插入中文问题

url=jdbc:mysql://localhost:3306/myemployees?characterEncoding=utf8

相关文章:

JDBC学习汇总

概念 JDBC&#xff1a;JDBC是Java提供的一套用来操作数据库的接口 通过Java代码操作数据库 1.确定数据库是可以正常使用&#xff08;MySQL服务是否正常开启&#xff09; 2.确定MySQL的账号和密码是正确的 3.确定MySQL版本和MySQL驱动版本匹配 4.在工程&#xff08;module&#…...

HarmonyOS—UI开发性能提升的推荐方法

注&#xff1a;本文转载自HarmonyOS官网文档 开发者若使用低性能的代码实现功能场景可能不会影响应用的正常运行&#xff0c;但却会对应用的性能造成负面影响。本章节列举出了一些可提升性能的场景供开发者参考&#xff0c;以避免应用实现上带来的性能劣化。 使用数据懒加载 开…...

英文科技论文写作与发表-常见英语写作困扰(第3章)

1.常见英语写作困扰 英语写作应该是越精炼越好。写完一个句子&#xff0c;建议尝试删除某个或某些单词&#xff0c;如果删除后句子意义基本不变&#xff0c;就应该删除。 1.1 所有格 使用所有格可以省去至少一个单词&#xff08;of&#xff09;,如&#xff1a;Kangs book T…...

video标签自动播放音视频并绘制波形图

html中的<video>标签可以用来播放常见的音视频格式&#xff0c;支持的格式包括:MP3、Ogg、WAV、AAC、MP4、WebM、AVI等&#xff0c;当然支持的格式也和浏览器和操作系统有关。这里以一个可以自动播放音视频并绘制波形图的页面为例说明一下<video>标签的用法。 vid…...

Netty—EventLoop

文章目录 一、EventLoopGroup 是什么&#xff1f;&#x1f914;️二、NioEventLoop 有哪些重要组成部分&#xff1f;&#x1f50d;三、NioEventLoop 的 thread 在何时启动&#xff1f;三、 run() 方法中线程在干嘛&#xff1f; 一、EventLoopGroup 是什么&#xff1f;&#x1f…...

[极客大挑战 2019]FinalSQL(bypass盲注)

这里是数字型注入&#xff0c;选择一个序号 fuzz ?id1这里过滤了很多东西 使用fuzzSQL字典&#xff0c;这是我自己定义编写的一个fuzz字典&#xff0c;内容较少 select from information . tables whereand " or | & union columns updatexml extractvalue databa…...

如何实现小程序与h5页面间的跳转

接到新需求&#xff0c;要在小程序页面内点击按钮实现跳转h5&#xff0c;一开始没接触过&#xff0c;还挺头疼的&#xff0c;但真正做起来&#xff0c;也就那么一回事啦&#xff0c;废话少说&#xff0c;直接上 1. 配置域名 先登录小程序开发平台&#xff0c;将页面需要跳转的…...

企业架构LNMP学习笔记9

nginx配置文件定义php-fpm服务&#xff1a; 编写测试文件&#xff1a; vim /usr/local/nginx/html/index.php 内容&#xff1a; <?phpphpinfo(); 在nginx的配置文件中配置&#xff1a; 修改配置文件&#xff0c;告知nginx如果收到.php结尾的请求&#xff0c;交由给php-…...

华为OD机试 - 二维伞的雨滴效应(Java JS Python)

题目描述 普通的伞在二维平面世界中,左右两侧均有一条边,而两侧伞边最下面各有一个伞坠子,雨滴落到伞面,逐步流到伞坠处,会将伞坠的信息携带并落到地面,随着日积月累,地面会呈现伞坠的信息。 1、为了模拟伞状雨滴效应,用二叉树来模拟二维平面伞(如下图所示),现在输…...

【HttpRunnerManager】搭建接口自动化测试平台操作流程

一、需要准备的知识点 1. linux: 安装 python3、nginx 安装和配置、mysql 安装和配置 2. python: django 配置、uwsgi 配置 二、我搭建的环境 1. Centos7 &#xff08;配置 rabbitmq、mysql 、Supervisord&#xff09; 2. python 3.6.8 &#xff08;配置 django、uwsgi&am…...

【C++】STL-常用算法-常用查找算法

0.前言 1.find #include <iostream> using namespace std;// 常用查找算法 find #include<vector> #include<algorithm>//查找 内置数据类型 void test01() {vector<int>v;for (int i 0; i < 10; i){v.push_back(i);}//查找 容器中 是否有 5 这个元…...

vue3 webpack打包流程及安装 (1)

npm run build 也可以打包 如果没有特殊需求 可以使用 效果其实是差不多的 --------------------------------------------------------------------------------------------------------------------------------- webpack网址 &#xff1a; 起步 | webpack 中文文档 (docsc…...

【C++】内联函数 ① ( 内联函数引入 | 内联函数语法 )

文章目录 一、内联函数引入1、内联函数引入2、代码示例 - 宏代码片段 与 内联函数 二、内联函数语法1、内联函数语法说明2、代码示例 - 内联函数基本语法 一、内联函数引入 1、内联函数引入 " 内联函数 " 是 C 语言中的一种特殊函数 , 其目的是为了提高程序的执行效率…...

聊聊springboot的ConfigurationProperties的绑定

序 本文主要研究一下springboot的ConfigurationProperties的绑定 ConfigurationPropertiesBindingPostProcessor org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java /*** {link BeanPostProcessor} to bind {link PropertySo…...

Mysql和Oracle的语法区别?

Mysql和Oracle是两种不同的关系型数据库。 MySQL通常在中小型应用程序、Web应用程序和小型企业中广泛使用&#xff0c;因为它易于学习和部署&#xff0c;而且成本较低。 Oracle数据库通常用于大型企业和复杂的企业级应用程序&#xff0c;因为它提供了高度可扩展性、高可用性…...

F - LIS on Tree

F - LIS on Tree (atcoder.jp) 问题描述&#xff1a;树上LIS。 普通LIS。O(n * n)。 void solve() {int n; cin>>n;vector<int> f(n 1),a(n1);for(int i 1; i < n; i) {cin>>a[i];f[i] 1;for(int j 1; j < i; j) {if(a[i] > a[j]) f[i] max…...

2023 年全国大学生数学建模B题目-多波束测线问题

B题目感觉属于平面几何和立体几何的问题&#xff0c;本质上需要推导几何变换情况&#xff0c;B题目属于有标准答案型&#xff0c;没太大的把握不建议选择&#xff0c;可发挥型不大。 第一问 比较简单&#xff0c;就一个2维平面的问题&#xff0c;但有点没理解&#xff0c;这个…...

qt creater11 翻译国际化教程教程:

先出效果图。 闲聊几句&#xff1a;qt这个翻译很方便&#xff0c;能直接导出项目里所有文字。 具体步骤如下&#xff1a; 在Qt中&#xff0c;我们可以使用QTranslator类来实现多语言切换。以下是一般步骤&#xff1a; 1. 在你的源代码中&#xff0c;所有需要翻译的字符串都…...

【AWS实验 】在 AWS Fargate 上使用 Amazon ECS 部署应用程序

文章目录 实验概览目标实验环境任务 1&#xff1a;连接到实验命令主机任务 2&#xff1a;将应用程序容器化任务 3&#xff1a;构建 Web2048 容器任务 4&#xff1a;创建 Amazon ECR 存储库并推送 Docker 映像任务 5&#xff1a;创建 ECS 集群任务 6&#xff1a;测试应用程序总结…...

matlab几种求解器的选择fsolve-sole-vpasolve

文章目录 fsolvesolvevpasovle总结vpasovle的结果fsovle的结果 fsolve 求数值解 result_xfsolve(my_fun,x0,options)参数: my_fun:待求解函数&#xff0c;作为一个.m文件 x0:初始值&#xff0c;向量&#xff0c;可以仅仅指定其中的几项solve 强大的求解器。在方程组中求解析…...

conda相比python好处

Conda 作为 Python 的环境和包管理工具&#xff0c;相比原生 Python 生态&#xff08;如 pip 虚拟环境&#xff09;有许多独特优势&#xff0c;尤其在多项目管理、依赖处理和跨平台兼容性等方面表现更优。以下是 Conda 的核心好处&#xff1a; 一、一站式环境管理&#xff1a…...

R语言AI模型部署方案:精准离线运行详解

R语言AI模型部署方案:精准离线运行详解 一、项目概述 本文将构建一个完整的R语言AI部署解决方案,实现鸢尾花分类模型的训练、保存、离线部署和预测功能。核心特点: 100%离线运行能力自包含环境依赖生产级错误处理跨平台兼容性模型版本管理# 文件结构说明 Iris_AI_Deployme…...

Admin.Net中的消息通信SignalR解释

定义集线器接口 IOnlineUserHub public interface IOnlineUserHub {/// 在线用户列表Task OnlineUserList(OnlineUserList context);/// 强制下线Task ForceOffline(object context);/// 发布站内消息Task PublicNotice(SysNotice context);/// 接收消息Task ReceiveMessage(…...

Vue3 + Element Plus + TypeScript中el-transfer穿梭框组件使用详解及示例

使用详解 Element Plus 的 el-transfer 组件是一个强大的穿梭框组件&#xff0c;常用于在两个集合之间进行数据转移&#xff0c;如权限分配、数据选择等场景。下面我将详细介绍其用法并提供一个完整示例。 核心特性与用法 基本属性 v-model&#xff1a;绑定右侧列表的值&…...

ssc377d修改flash分区大小

1、flash的分区默认分配16M、 / # df -h Filesystem Size Used Available Use% Mounted on /dev/root 1.9M 1.9M 0 100% / /dev/mtdblock4 3.0M...

Java多线程实现之Callable接口深度解析

Java多线程实现之Callable接口深度解析 一、Callable接口概述1.1 接口定义1.2 与Runnable接口的对比1.3 Future接口与FutureTask类 二、Callable接口的基本使用方法2.1 传统方式实现Callable接口2.2 使用Lambda表达式简化Callable实现2.3 使用FutureTask类执行Callable任务 三、…...

ETLCloud可能遇到的问题有哪些?常见坑位解析

数据集成平台ETLCloud&#xff0c;主要用于支持数据的抽取&#xff08;Extract&#xff09;、转换&#xff08;Transform&#xff09;和加载&#xff08;Load&#xff09;过程。提供了一个简洁直观的界面&#xff0c;以便用户可以在不同的数据源之间轻松地进行数据迁移和转换。…...

CMake控制VS2022项目文件分组

我们可以通过 CMake 控制源文件的组织结构,使它们在 VS 解决方案资源管理器中以“组”(Filter)的形式进行分类展示。 🎯 目标 通过 CMake 脚本将 .cpp、.h 等源文件分组显示在 Visual Studio 2022 的解决方案资源管理器中。 ✅ 支持的方法汇总(共4种) 方法描述是否推荐…...

管理学院权限管理系统开发总结

文章目录 &#x1f393; 管理学院权限管理系统开发总结 - 现代化Web应用实践之路&#x1f4dd; 项目概述&#x1f3d7;️ 技术架构设计后端技术栈前端技术栈 &#x1f4a1; 核心功能特性1. 用户管理模块2. 权限管理系统3. 统计报表功能4. 用户体验优化 &#x1f5c4;️ 数据库设…...

【笔记】WSL 中 Rust 安装与测试完整记录

#工作记录 WSL 中 Rust 安装与测试完整记录 1. 运行环境 系统&#xff1a;Ubuntu 24.04 LTS (WSL2)架构&#xff1a;x86_64 (GNU/Linux)Rust 版本&#xff1a;rustc 1.87.0 (2025-05-09)Cargo 版本&#xff1a;cargo 1.87.0 (2025-05-06) 2. 安装 Rust 2.1 使用 Rust 官方安…...