idea连接mysql的学生管理系统代码
时间: 2023-10-21 17:07:18 浏览: 50
以下是一个基本的学生管理系统的代码,使用了Java和MySQL,其中包含了连接MySQL数据库的代码:
```
import java.sql.*;
public class StudentManagementSystem {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, age FROM Students";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.println(", Age: " + age);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
```
在该代码中,我们首先定义了需要使用的数据库驱动和数据库的URL、用户名和密码。然后,在`main`方法中,我们首先通过`DriverManager.getConnection`方法连接到MySQL数据库,然后使用`conn.createStatement`方法创建一个用于执行SQL语句的`Statement`对象。在这个例子中,我们执行了一个简单的查询,打印出了学生的ID、姓名和年龄。最后,我们关闭了`ResultSet`、`Statement`和`Connection`对象,释放了与之关联的所有资源。
请注意,这只是一个非常简单的例子,用于演示如何连接到MySQL数据库和执行一些基本的SQL操作。在实际开发中,应该考虑安全性、性能和其他因素,并且可能需要使用更高级的技术和框架来构建更复杂的应用程序。