Java编写一个程序,连接MySQL服务器192.168.1.1:3306(root:123456)上的数据库MISinfo,从学生表中检索所有字段和记录,并用动态光标迭代记录。
时间: 2024-03-25 10:35:21 浏览: 21
好的,以下是Java连接MySQL并从学生表中检索所有字段和记录的代码示例:
```java
import java.sql.*;
public class MySQLConnector {
public static void main(String[] args) {
String url = "jdbc:mysql://192.168.1.1:3306/MISinfo";
String user = "root";
String password = "123456";
try {
// 加载MySQL驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 获取数据库连接
Connection conn = DriverManager.getConnection(url, user, password);
// 创建Statement对象
Statement stmt = conn.createStatement();
// 执行查询语句
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
// 动态光标迭代记录
while (rs.next()) {
// 获取每条记录的字段值
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String gender = rs.getString("gender");
String department = rs.getString("department");
// 输出每条记录
System.out.println("id: " + id +
", name: " + name +
", age: " + age +
", gender: " + gender +
", department: " + department);
}
// 关闭ResultSet对象
rs.close();
// 关闭Statement对象
stmt.close();
// 关闭数据库连接
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们首先定义了连接MySQL数据库所需的URL、用户名和密码。然后,我们加载了MySQL驱动程序并获取了数据库连接。接着,创建了一个Statement
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)