如何使用JDBC连接数据库、操作数据库
程序员文章站
2024-03-22 17:11:10
...
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
本文将会用IntelliJ IDEA演示如何使用JDBC技术连接并操作数据库,可以当作模板使用。
使用步骤
1.下载Jar包
访问Maven官网下载,这里使用mysql-connector-java8.0.19为例,点击右边跳转下载
2.导入Jar包
3.使用JDBC修改数据库的内容
这里演示将db1数据库中user表中id=1的age从10改为20
执行代码前的数据库情况
跑一下项目看结果
执行代码后的数据库情况
代码如下(自取修改):
public class JDBCDemo1 {
public static void main(String[] args) throws Exception{
//1.注册驱动(反射的方式)
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取数据库连接
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?serverTimezone=UTC","root","root");
//3.创建执行sql的对象
Statement stmt= conn.createStatement();
//4.定义sql语句
String sql="update user set age=20 where id=1";
//5.执行sql
int index = stmt.executeUpdate(sql);
//6.处理获取
System.out.println(index);
//7.释放资源(先开后关)
stmt.close();;
conn.close();
}
}
考虑异常处理的最终版
public class JDBCDemo1 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//1.注册驱动(反射的方式)
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取数据库连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?serverTimezone=UTC","root","root");
//3.创建执行sql的对象
stmt = conn.createStatement();
//4.定义sql语句
String sql="update user set age=20 where id=1";
//5.执行sql
int rs = stmt.executeUpdate(sql);
//6.处理获取.遍历结果集,并获取查询结果
System.out.println(rs);
}catch(Exception e) {
e.printStackTrace();
}finally {
//7.释放资源(先开后关)
if(stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
stmt = null;
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
conn = null;
}
}
}
}
}
推荐阅读
-
IDEA使用JDBC连接操作mysql数据库
-
使用JDBC连接数据库实际操作
-
JAVA使用JDBC连接MySQL数据库操作
-
如何使用JDBC连接数据库、操作数据库
-
(JDBC)如何通过IDEA使用Java来连接MySQL数据库并进行操作
-
kylin -- 使用JDBC连接操作Kylin
-
DBeaver数据库管理工具连接Sybase数据库使用体验 博客分类: SYBASE ASESYBASE [ASA|IQ|SUP|...]OracleMySQLDB2|PostgreSQL|SQLite|OthersSoftware Architecture|OODatabase General
-
Python进阶学习_连接操作Redis数据库
-
使用python操作MongoDB数据库
-
jdbc连接mysql oracle sql server数据库的连接字符串