当前位置:网站首页>如何使用JDBC操作数据库
如何使用JDBC操作数据库
2022-07-28 02:47:00 【似朝阳】
文章目录
以Mysql为例,我们看一下Java怎么与数据库链接
1.导入数据库驱动jar包
首先第一步就是在网上下载一个mysql的数据库驱动jar包,类似mysql-connector-java-5.1.20-bin.jar。新建一个JAVA项目,在项目下面创建一个lib文件夹,将驱动jar文件拷贝到lib文件夹中。
接着需要将该JAR包加入到项目的build path变量中。鼠标右键-build path->configure build path … 在弹出的界面中点击Add jars 选中驱动jar包将之添加到build path变量中。
2.注册驱动
导入了驱动,那么需要在程序中注册驱动,意思就是告诉程序可以对这个驱动对应的数据库进行操作。
Class.forName(driver);
这句话会有异常,然后处理方法很简单,只需要在定义类的时候抛出异常,或者try/catch就可以
就像这样
public void QueeyAll() throws Exception{
}
3.获取数据库连接对象Connection
这个连接对象就是java代码和数据库的桥梁,通过这个连接对象(桥梁)连接数据库。
String driver = "com.mysql.jdbc.Driver";//MySQL数据库的驱动程序名
String url = "jdbc:mysql://localhost:3306/oldsix?useUnicode=true&characterEncoding=utf- 8&useSSL=false";//数据库连接字符串
String user = "root";//用户名
String password = "******";//密码
Connection conn = DriverManager.getConnection(url,user,password);
用户名跟密码就是你自己使用的数据库的账号密码
4.定义SQL语句
连接了数据库,就是要对数据库进行操作。所以要定义SQL语句,其实就是你要对数据库进行什么操作,放在SQL语句中(不完全正确的比喻,SQL语句就是对数据库的操作的容器)。
就比如我想要查询user表中的所有数据
ResultSet result = null;
String sql = "select * from user";
result = stmt.executeQuery(sql);
5.获取执行SQL语句的对象 Statement
定义好要对数据库进行的操作,那么谁来帮我执行?——执行SQL语句的对象 Statement。所以要获取这个对象。
Statement stmt = null;
stmt = conn.createStatement();
6.执行SQL,接收返回的结果,处理返回结果
有了执行对象那么就开始执行操作对数据库进行操作,并且返回操作结果。用户对返回结果进行处理
ResultSet result = null;
result = stmt.executeQuery(sql);
7.释放资源
执行完了一系列的操作后,那么要释放资源。相当于有人帮你干活,干完了之后,要让别人走吧。
result.close();
stmt.close();
conn.close();
做完这些工作我们就可以对数据库进行操作了
边栏推荐
猜你喜欢

Why is it that when logging in, you clearly use the account information already in the database, but still display "user does not exist"?
![[stream] basic knowledge of stream](/img/33/0bd85f7e029c81d0c20f463ebb972a.png)
[stream] basic knowledge of stream

Win11如何重命名音频设备

Web server

Engineering Geology Practice - engineering geology problem set

Scheme sharing | experts gather to jointly explore accent AI speech recognition

max_pool2d(): argument ‘input‘ (position 1) must be Tensor, not NoneType

R 笔记 MICE

会议OA项目之我的审批&&签字功能

Full of dry goods, hurry in!!! Easy to master functions in C language
随机推荐
Record of a cross domain problem
style=“width: ___“ VS width=“___“
在线问题反馈模块实战(十六):实现查详情功能
ThreadLocal使用场景
Yiwen teaches you to distinguish between continuous integration, continuous delivery and continuous deployment
NPDP candidates! The exam requirements for July 31 are here!
IO analog serial port of stm32
Random forest and integration method learning notes
Note that these regions cannot take the NPDP exam in July
Redis持久化机制
Decision tree and random forest learning notes (1)
My approval & signature function of conference OA project
CAD creation group is not combined?
随机森林与集成方法学习笔记
什么是虚函数?
蓝桥杯原题
[stream] parallel stream and sequential stream
Design of the multi live architecture in different places of the king glory mall
关于权重衰退和丢弃法
上位机与MES对接的几种方式