mysql连接java学生系统代码示例
时间: 2023-08-11 15:41:42 浏览: 50
以下是一个连接MySQL数据库并进行查询的Java示例代码,假设我们要查询学生信息:
```java
import java.sql.*;
public class StudentSystem {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载MySQL驱动
Class.forName("com.mysql.jdbc.Driver");
// 连接MySQL数据库
String url = "jdbc:mysql://localhost:3306/student_system";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
// 查询学生信息
stmt = conn.createStatement();
String sql = "SELECT * FROM student";
rs = stmt.executeQuery(sql);
// 输出查询结果
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 {
// 关闭数据库连接
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
其中,`com.mysql.jdbc.Driver` 是MySQL的JDBC驱动类,需要先加载才能连接数据库。`student_system` 是数据库名,`root` 是MySQL的用户名,`123456` 是MySQL的密码。在查询学生信息时,我们使用了`Statement`对象执行SQL语句,并使用`ResultSet`对象获取查询结果。最后,我们需要关闭数据库连接,以释放数据库资源。