JDBC 保姆级【快速入门】

JDBC 快速入门


一、JDBC是什么?

JDBC是Sun公司提供的 一套通用的用于数据库操作的接口,独立于特定数据库管理系统。而不同的数据库厂商针对这套接口,提供的不同实现,即为不同的数据库驱动。


二、JDBC用来干什么?

JDBC定义了一套用来访问数据库的标准Java类库,使用这些类库可以方便地访问数据库资源。简言之:JDBC实现了通过Java语言来访问和操作数据库资源。


三、JDBC如何使用?

准备工作: 下载 mysql 的驱动 jar 包,并导入(案例采用8.0版本)

第一步: 注册驱动

Class.forName("com.mysql.cj.jdbc.Driver");

第二步: 获取连接对象

String url = "jdbc:mysql://localhost:3306/db1?useSSL=false";
String username = "root";
String password = "abc123";
Connection conn = DriverManager.getConnection(url, username, password);

第三步: 定义SQL

String sql = "update emp set salary = 2000 where id = 1";

第四步: 获取执行SQL的对象

Statement stmt = conn.createStatement();

第五步: 执行SQL

int count = stmt.executeUpdate(sql);

第六步: 处理结果

System.out.println(count);

最后一步: 释放资源

stmt.close();
conn.close();

四、JDBC进阶版使用

思考:当数据库的信息采用外部文件书写时,应该如何进行改动?

jdbc.properties 具体内容为:

user=root
password=abc123
url=jdbc:mysql://localhost:3306/db1?useSSL=false
className=com.mysql.cj.jdbc.Driver

注意:properties文件放在resources目录下

代码演示:

//1. 加载配置文件
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties info = new Properties();
info.load(is);

//2. 获取配置信息
String url = info.getProperty("url");
String user = info.getProperty("user");
String password = info.getProperty("password");
String className = info.getProperty("className");

//3. 加载驱动
Class.forName(className);

//4. 获取连接
Connection conn = DriverManager.getConnection(url, user, password);

//5. 编写SQL
String sql = "update employee set salary = 2000 where id = 10001";

//6. 获取执行SQL的对象
Statement stmt = conn.createStatement();

//7. 执行SQL
int count = stmt.executeUpdate(sql);
System.out.println(count);

//8. 资源关闭
stmt.close();
conn.close();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值