已知student表有姓名,年龄,生日,兴趣爱好四个字段。使用JDBC连接后,查询出所有的记录并输出。(注明JDBC连接的步骤)
时间: 2024-04-30 14:21:51 浏览: 6
JDBC连接步骤如下:
1. 加载数据库驱动程序
2. 创建数据库连接
3. 创建Statement对象
4. 执行SQL语句
5. 处理结果集
6. 关闭连接
以下是使用Java代码实现查询student表的所有记录并输出的示例:
```java
import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/your_database_name";
static final String USER = "your_username";
static final String PASS = "your_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 加载数据库驱动程序
Class.forName(JDBC_DRIVER);
// 创建数据库连接
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 创建Statement对象
stmt = conn.createStatement();
// 执行SQL语句
String sql = "SELECT * FROM student";
ResultSet rs = stmt.executeQuery(sql);
// 处理结果集
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
Date birthday = rs.getDate("birthday");
String hobby = rs.getString("hobby");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Birthday: " + birthday);
System.out.println("Hobby: " + hobby);
System.out.println();
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// 处理JDBC错误
se.printStackTrace();
} catch (Exception e) {
// 处理Class.forName错误
e.printStackTrace();
} finally {
// 关闭资源
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se2) {
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
```
需要将代码中的 `your_database_name`、`your_username` 和 `your_password` 替换成实际的数据库名、用户名和密码。