用java实现完成数据库操作的代码演示,把相关代码写在异常处理的代码块中。要求: 1.选择自己熟悉的一种数据库,建立一个学生信息表 2.完成对数据表的增删改查操作
时间: 2024-10-17 13:10:02 浏览: 27
如何用java代码写数据库数据
5星 · 资源好评率100%
在Java中,我们可以使用JDBC (Java Database Connectivity) 来连接并操作数据库。这里以MySQL为例,我会展示如何创建数据库、表以及基本的CRUD操作,异常处理部分会包含常见的SQL错误处理。
首先,确保已经添加了mysql-connector-java驱动到项目中:
```xml
<!-- pom.xml -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
```
然后,编写数据库操作相关的Java代码,包括异常处理:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DatabaseManager {
private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "username";
private static final String PASSWORD = "password";
// 连接数据库
private Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
// 创建学生信息表
public void createStudentTable() throws SQLException {
String sql = "CREATE TABLE IF NOT EXISTS Students (" +
"id INT AUTO_INCREMENT PRIMARY KEY," +
"name VARCHAR(50) NOT NULL," +
"age INT NOT NULL)";
try (Connection conn = getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println("Error creating table: " + e.getMessage());
}
}
// 插入学生信息
public void insertStudent(String name, int age) {
String sql = "INSERT INTO Students (name, age) VALUES (?, ?)";
try (Connection conn = getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println("Error inserting student: " + e.getMessage());
}
}
// 更新学生信息
public void updateStudent(int id, String newName, int newAge) {
String sql = "UPDATE Students SET name = ?, age = ? WHERE id = ?";
try (Connection conn = getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, newName);
pstmt.setInt(2, newAge);
pstmt.setInt(3, id);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println("Error updating student: " + e.getMessage());
}
}
// 删除学生信息
public void deleteStudent(int id) {
String sql = "DELETE FROM Students WHERE id = ?";
try (Connection conn = getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println("Error deleting student: " + e.getMessage());
}
}
// 关闭连接
public void closeConnection(Connection conn) throws SQLException {
if (conn != null && !conn.isClosed()) {
conn.close();
}
}
}
```
在这个示例中,我们创建了一个`DatabaseManager`类来封装数据库操作。每个操作都包含在一个try-catch块内,捕获可能出现的`SQLException`。如果操作成功,`executeUpdate()`将返回受影响的行数;如果不成功,我们只是打印出错误消息,实际应用中可能会有更详细的日志记录或事务管理。
阅读全文