Java连接数据库(学生管理系统案例,可以实现增删改查)
时间: 2023-11-26 09:06:30 浏览: 28
好的,我可以帮你解决这个问题。你需要先下载并安装Java的数据库驱动程序,通常是一个.jar文件。接下来,在你的Java代码中使用JDBC连接到数据库,配置数据库的连接信息,比如说数据库的URL、用户名和密码。然后,可以使用Java代码执行SQL语句来实现对数据库的增删改查操作。以下是一个简单的Java连接MySQL数据库的示例代码:
```java
import java.sql.*;
public class StudentManagementSystem {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENT";
static final String USER = "root";
static final String PASS = "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);
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();
}
}
}
}
```
这段代码可以连接到名为STUDENT的MySQL数据库,并查询其中所有学生的信息。你可以根据需要修改代码来实现增删改查操作。