文章目录
- 视频:JDBC插入数据
- 环境准备
- 写插入数据
- 属性配置
- 属性配置
视频:JDBC插入数据
环境准备
MySQL环境
小皮面板
提供MySQL环境
写插入数据
属性配置
声明变量
属性配置
# . properties 是一个特俗的map 集合
# key : 字符串 value : 字符串
# . propertie 集合经常用于 属性配置
# 在我们这里配置 数据库的基本信息
# 用户名 密码 端口 库名
# key=value
# 属性配置的信息被 Java程序读取
# 读取规则 (“key”) 拿到对应的 value
# = 左边 随便写 ,右边必须一模一样
# key = value
#mysql 驱动信息
driver=com.mysql.cj.jdbc.Driver
#连接哪个电脑 ,的哪个软件 3306
# 就代表连接的是mysqlurl=jdbc:mysql://127.0.0.1:3306/yanyu
username=root
password=root
插入数据
package com.yanyu;import java.sql.*;
import java.util.ResourceBundle;public class InsertTest1 {
// 利用资源绑定器去读取 mydb.propertiespublic static void main(String[] args) {
// ctrl 单机
// RB ctrl alt vResourceBundle bundle = ResourceBundle.getBundle("db//mydb");System.out.println(bundle);
// 通过 bundle 对象 读取 每一个 value
// # 读取规则 (“key”) 拿到对应的 valueString url = bundle.getString("url");String driver = bundle.getString("driver");// ctrl dString username = bundle.getString("username");// ctrl dString password = bundle.getString("password");// ctrl d
// System.out.println(driver);
// System.out.println(url);
// System.out.println(username);
// System.out.println(password);// 放大作用域 声明 变量
// 连接对象Connection con = null;
// int jn = 0;
// 操作对象Statement st = null;// 结果集对象ResultSet rs = null;
// 注册驱动try {Class.forName(driver);
// 连接对象con = DriverManager.getConnection(url,username,password);
//写 SQL
//String sql = "insert into student(name,stuid,major) value('烟雨2','1004','软件技术')";
// 操作对象st = con.createStatement();
// 执行插入语句st.execute(sql);} catch (ClassNotFoundException e) {throw new RuntimeException(e);} catch (SQLException e) {throw new RuntimeException(e);} finally {
// 关闭数据流 判断是否为空
// con st rsif (rs != null) {try {rs.close();} catch (SQLException e) {throw new RuntimeException(e);}}if (st != null) {try {st.close();} catch (SQLException e) {throw new RuntimeException(e);}}if (con != null) {try {con.close();} catch (SQLException e) {throw new RuntimeException(e);}}}}
}
结果