java jdbc查询mysql
时间: 2023-11-27 19:44:05 浏览: 39
好的,针对您的问题,您可以按照以下步骤进行操作:
1. 导入 JDBC 驱动包
2. 加载驱动类
3. 建立连接
4. 创建 Statement 对象
5. 执行 SQL 语句
6. 处理结果集
7. 关闭连接
下面是一个简单的示例代码:
```java
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1. 导入 JDBC 驱动包
Class.forName("com.mysql.jdbc.Driver");
// 2. 加载驱动类
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
// 3. 建立连接
conn = DriverManager.getConnection(url, user, password);
// 4. 创建 Statement 对象
stmt = conn.createStatement();
// 5. 执行 SQL 语句
String sql = "SELECT * FROM student";
rs = stmt.executeQuery(sql);
// 6. 处理结果集
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);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 7. 关闭连接
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```