在Java中操作MySQL数据库,通常使用JDBC(Java Database Connectivity)API。以下是一个简单的示例,展示了如何连接到MySQL数据库、执行增删改查操作。
import java.sql.*; public class MySQLExample { // JDBC URL, username, and password of MySQL server static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydb"; static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { // 1. Register JDBC driver Class.forName("com.mysql.cj.jdbc.Driver"); // 2. Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(JDBC_URL, USER, PASS); // 3. Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); // Insert operation String sqlInsert = "INSERT INTO employees (id, name, age, position) VALUES (1, 'John Doe', 30, 'Manager')"; stmt.executeUpdate(sqlInsert); System.out.println("Inserted record into the table..."); // Update operation String sqlUpdate = "UPDATE employees SET age = 31 WHERE id = 1"; stmt.executeUpdate(sqlUpdate); System.out.println("Updated record in the table..."); // Delete operation String sqlDelete = "DELETE FROM employees WHERE id = 1"; stmt.executeUpdate(sqlDelete); System.out.println("Deleted record from the table..."); // Select operation String sqlSelect = "SELECT id, name, age, position FROM employees"; ResultSet rs = stmt.executeQuery(sqlSelect); // Extract data from result set while (rs.next()) { // Retrieve by column name int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); String position = rs.getString("position"); // Display values System.out.print("ID: " + id); System.out.print(", Name: " + name); System.out.print(", Age: " + age); System.out.println(", Position: " + position); } rs.close(); } catch (SQLException se) { // Handle errors for JDBC se.printStackTrace(); } catch (Exception e) { // Handle errors for Class.forName e.printStackTrace(); } finally { // Finally block used to close resources try { if (stmt != null) stmt.close(); } catch (SQLException se2) { } // nothing we can do try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } // end finally try } // end try System.out.println("Goodbye!"); } // end main } // end MySQLExample说明
注册JDBC驱动:
使用Class.forName("com.mysql.cj.jdbc.Driver")注册MySQL JDBC驱动。打开连接:
使用DriverManager.getConnection(JDBC_URL, USER, PASS)连接到MySQL数据库。创建Statement对象:
使用conn.createStatement()创建一个Statement对象,用于执行SQL语句。执行增删改查操作:
使用stmt.executeUpdate(sql)执行插入、更新和删除操作。使用stmt.executeQuery(sql)执行查询操作,并使用ResultSet对象处理查询结果。关闭资源:
在finally块中关闭Statement和Connection对象,释放资源。依赖管理如果你使用Maven来管理项目依赖,可以在pom.xml中添加以下依赖:
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> </dependencies>
这样,你就可以在Java项目中使用JDBC API来操作MySQL数据库了。
网友回复