文章目录
- 准备数据库
- 添加数据
- 引入数据库依赖包
准备数据库
自行安装软件,利用小皮内嵌的数据
添加数据
引入数据库依赖包
结构
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3308/yanyu
user=root
password=root
package com.yanyu;
import java.sql.*;
import java.util.ResourceBundle;
public class JDBCTest2 {
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle("com\\resources\\db");
String driver = bundle.getString("driver");
// System.out.println(driver);
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
// System.out.println(password);
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName(driver);
// 数据库连接对象
con = DriverManager.getConnection(url,user,password);
// 写SQL
String sql = "insert into user(name,password) values('yanyu666','123456')";
// mysql 的字符串 统一用 单引号 ''
// 获取操作对象
st = con.createStatement();
// 执行SQL语句
st.execute(sql);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
// 关流:处理异常,使用新的 捕捉器
// 从 小到大 进行 关流 rs st con
if (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);
}
}
}
}
}