mysql与java连接后?的使用
时间: 2024-02-20 07:01:59 浏览: 14
连接 MySQL 数据库和 Java 代码可以通过 JDBC API 来实现。下面是连接 MySQL 数据库的步骤:
1. 导入 MySQL JDBC 驱动程序:将 MySQL JDBC 驱动程序的 JAR 文件添加到 Java 项目的类路径中。
2. 加载驱动程序:使用 Class.forName() 方法来加载 MySQL JDBC 驱动程序。
3. 建立连接:使用 DriverManager.getConnection() 方法来建立与 MySQL 数据库的连接。需要提供连接字符串、用户名和密码。
4. 创建 Statement 对象:使用 Connection.createStatement() 方法创建 Statement 对象,用于执行 SQL 查询。
5. 执行 SQL 查询:使用 Statement.executeQuery() 方法执行 SQL 查询,并获取查询结果。
6. 处理查询结果:使用 ResultSet 对象来处理查询结果。
下面是一个示例代码:
```java
import java.sql.*;
public class MySQLExample {
public static void main(String[] args) {
try {
// 导入 MySQL JDBC 驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立连接
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase", "myuser", "mypassword");
// 创建 Statement 对象
Statement stmt = conn.createStatement();
// 执行 SQL 查询
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
// 处理查询结果
while (rs.next()) {
// 读取查询结果
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println(id + "\t" + name + "\t" + age);
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个示例代码连接到本地 MySQL 数据库,查询名为 "mydatabase" 的数据库中的 "mytable" 表,并打印查询结果。你需要将 "mydatabase"、"myuser" 和 "mypassword" 替换为你自己的数据库名称、用户名和密码。