怎么写java和mysql的交互代码
时间: 2024-02-17 10:01:04 浏览: 17
要在 Java 中使用 MySQL 数据库,需要使用 JDBC(Java Database Connectivity) API。下面是一个简单的 Java 程序,演示如何连接 MySQL 数据库并执行一些基本的查询操作:
```java
import java.sql.*;
public class MySQLExample {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 连接 MySQL 数据库
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "username", "password");
// 创建 SQL 语句
String sql = "SELECT * FROM customers";
// 创建 Statement 对象
stmt = conn.createStatement();
// 执行 SQL 查询
ResultSet rs = stmt.executeQuery(sql);
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String address = rs.getString("address");
System.out.println("ID: " + id + ", Name: " + name + ", Address: " + address);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭连接和 Statement 对象
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在上面的示例中,我们使用 `DriverManager.getConnection()` 方法连接 MySQL 数据库,并使用 `Statement` 对象执行 SQL 查询。我们还遍历查询结果集并打印每个行的数据。最后,我们关闭连接和 Statement 对象。
请注意,上述示例仅用于演示目的。在实际应用中,应该使用 `PreparedStatement` 对象来执行 SQL 查询,以避免 SQL 注入攻击。