JDBC(Java Database Connectivity)是Java语言中用于连接数据库的标准API。它提供了一种统一的接口,使得Java程序能够与各种关系型数据库进行交互。MySQL是一种流行的关系型数据库管理系统,JDBC连接MySQL数据库就是通过JDBC API来操作MySQL数据库。
JDBC连接MySQL数据库主要有两种方式:
JDBC连接MySQL数据库广泛应用于各种Java应用中,包括但不限于:
以下是一个简单的JDBC连接MySQL数据库并进行增删改查操作的示例代码:
import java.sql.*;
public class JDBCDemo {
// JDBC URL, username and password of MySQL server
static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册JDBC驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 打开连接
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(JDBC_URL, USER, PASS);
// 执行查询
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
ResultSet rs;
// 查询数据
sql = "SELECT id, name, age FROM employees";
rs = stmt.executeQuery(sql);
while (rs.next()) {
// 检索每一行数据
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// 显示数据
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
// 插入数据
sql = "INSERT INTO employees(name, age) VALUES('John Doe', 30)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
// 更新数据
sql = "UPDATE employees SET age = 31 WHERE name = 'John Doe'";
stmt.executeUpdate(sql);
System.out.println("Updated records in the table...");
// 删除数据
sql = "DELETE FROM employees WHERE name = 'John Doe'";
stmt.executeUpdate(sql);
System.out.println("Deleted records from the table...");
} catch (SQLException se) {
// 处理JDBC错误
se.printStackTrace();
} catch (Exception e) {
// 处理Class.forName错误
e.printStackTrace();
} finally {
// 关闭资源
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
} // 什么都不做
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
通过以上步骤,您可以成功连接MySQL数据库并执行增删改查操作。如果遇到问题,请根据错误信息进行排查和解决。
领取专属 10元无门槛券
手把手带您无忧上云