Java操作SQL数据库(JDBC)
2024-08-24 17:35:07
0.引入驱动jar包
使用jdbc进行具体操作前,需要引入相关数据库的jar包, 或者使用mave管理依赖
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.34.0</version>
</dependency>
1.加载驱动
Class.forName(DRIVER);
2.获取数据库连接对象
Connection conn=DriverManager.getConnection(URL);
3.创建(预处理)语句对象
普通语句对象
Statement stmt=conn.createStatement();
预处理语句对象
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setXxx(int parameterIndex, Xxx x); // 参数索引从1开始
4.执行sql语句
普通语句对象执行sql
boolean b=stmt.execute(sql);
int i=stmt.executeUpdate(sql);
ResultSet resultSet=stmt.executeQuery(sql);
预处理语句对象执行sql
int i=pstmt.executeUpdate();
ResultSet resultSet=pstmt.executeQuery();
5.处理结果集
while(resultSet.next())
{
int id=resultSet.getInt("id");
String name=resultSet.getString("name");
}
6.关闭结果集,语句,连接
resultSet.close();
stmt.close();
conn.close();
jdbc工具类封装
在类路径下创建配置文件
mysql.properties
DRIVER=com.mysql.cj.jdbc.Driver
URL=jdbc:mysql://localhost:3306/test
USER=root
PASSWORD=root
DBUtil.java
public class DBUtil
{
private static final String URL;
private static final String USER;
private static final String PASSWORD;
private DBUtil(){}
static
{
// 从properties文件中加载配置信息
ResourceBundle bundle=ResourceBundle.getBundle("mysql");
String DRIVER=bundle.getString("DRIVER");
URL=bundle.getString("URL");
USER=bundle.getString("USER");
PASSWORD=bundle.getString("PASSWORD");
try
{
Class.forName(DRIVER);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException
{
return DriverManager.getConnection(URL,USER,PASSWORD);
}
}
最新文章
- mysql导入导出数据库命令
- Linux内核之内存管理完全剖析
- Java基础09 类数据与类方法
- Summary Ranges leetcode
- hdu4417 Super Mario
- 对于查询调优,你需要的不止STATISTICS IO
- July 05th. 2018, Week 27th. Thursday
- body标签中l的相关标签
- git使用:本地项目推送到gitlab
- 如何修复“网络路径”,错误代码0x80070035
- Python - 关于代码阅读的一些建议
- 【杂谈】Tomcat 之 Lifecycle接口
- oracle 索引的几种方式
- 搭建ntp服务器
- python调用powershell、远程执行bat
- 【C++】数组-二分法查找
- 20155315 2016-2017-2《Java程序设计》课程总结
- Linux vim编辑器常用命令
- java网络编程TCP传输—流操作—服务端反馈与客户端接收
- ssm框架整合配置文件
热门文章
- C# 给PDF签名时添加时间戳的2种方法(附VB.NET代码)
- [bug] PowerDesigner的association按钮灰色不能使用
- TrueCrypt与CryptSetup双系统全盘加密(图文)
- Linux 系统中如何查看日志 (常用命令) tail -f
- 7.12-7.19 id、w、who、last、lastb、lastlog
- 014.Python函数
- Module not found: Error: Can&#39;t resolve &#39;less-loader&#39; in &#39; xxx&#39; (Day_40)
- [leetcode] 68. 文本左右对齐(国区第240位AC的~)
- 在Docker中安装MongoDB
- Go语言web开发---Beego基础