- 一、java连接数据库
- 1. 前置要求
- 2. java对数据库进行操作
- 2.1 连接数据库
- 2.2 查询数据
- 2.3 插入数据
- 2.4 更新数据
- 2.5 删除数据
- 使用工具
eclipse mysql - 下载JDBC驱动
- 将驱动加载到eclipse
在java项目下新建一个lib文件夹,将驱动复制到该文件夹下
右键项目build path–>configure build path–>libraries–>add jars… 将驱动加载进去
记得apply
DBConnection.java
public class DBConnection {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=CST&characterEncoding=utf-8";
String user = "root";
String password = "123456";
public Connection con;
//测试是否连接
public DBConnection() {
try {
//加载驱动,注册jdbc驱动
Class.forName(driver);
//连接数据库
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed()) {
System.out.println("Succeeded connecting to the Database!");
}
}catch(Exception e){
e.printStackTrace();
}
}
//定义关闭数据库函数
public void close() {
try {
this.con.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
2.2 查询数据
sql_class.java 部分代码
public static void show() {
String sql = "select * from info";
//调用DBConnection 类
DBConnection db = new DBConnection();
try {
//通过connection创建一个数据库操作对象statement(类似python的curson游标对象)
Statement stmt = db.con.createStatement();
//结果集对象rs:executeQuery()方法会把数据库响应的查询结果存放在ResultSet类对象中供我们使用
ResultSet rs = stmt.executeQuery(sql);
//返回结果集的每一行
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String age = rs.getString("age");
System.out.println(id+name+age);
}
rs.close();
stmt.close();
db.close();
}catch(Exception e){
e.printStackTrace();
}
}
在main函数里调用
public static void main(String[] args) {
show();
}
运行就可以看到结果
- 代码
public static void adddata(String name,String age) {
String sql = "insert into info(name,age)values(?,?)";
DBConnection db = new DBConnection();
try {
//PreparedStatement对象已预编译过,其执行速度要快于Statement对象
//因此,多次执行的 SQL 语句经常创建为 PreparedStatement 对象,以提高效率。
PreparedStatement preStmt = db.con.prepareStatement(sql);
preStmt.setString(1, name);
preStmt.setString(2, age);
//用于执行insert、update或delete语句以及SQLDDL(数据定义语言)语句
preStmt.executeUpdate();
preStmt.close();
db.close();
}catch(Exception e) {
e.printStackTrace();
}
}
mian函数里记得调用
public static void main(String[] args) {
adddata("陈六","32");
show();
}
- 结果
- 代码
public static void update(String name,String age,String id) {
String sql = "update info set name=?,age=? where id=?";
DBConnection db = new DBConnection();
try {
PreparedStatement preStmt = db.con.prepareStatement(sql);
preStmt.setString(1, name);
preStmt.setString(2, age);
preStmt.setString(3, id);
preStmt.executeUpdate();
preStmt.close();
db.close();
}catch(Exception e) {
e.printStackTrace();
}
}
main函数加入
update("刘七","35","4");
- 结果
- 代码
public static void delete(String id) {
String sql = "delete from info where id=?";
DBConnection db = new DBConnection();
try {
PreparedStatement preStmt = db.con.prepareStatement(sql);
preStmt.setString(1, id);
preStmt.executeUpdate();
preStmt.close();
db.close();
}catch(Exception e) {
e.printStackTrace();
}
}
main函数
delete("4");
- 结果



