今天写数据库的实验五,使用Java写了一个十分简易的数据库,连输入都没有,只是证明我用Java连上了sqlserver,代码如下:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Main { public static void main(String[] args) { String url = "jdbc:sqlserver://localhost:1433;databaseName=YourDatabase"; String user = "username"; String password = "password"; try (Connection conn = DriverManager.getConnection(url, user, password)) { // 插入数据 String insertSql = "INSERT INTO students (name, age, gender, class) VALUES (?, ?, ?, ?)"; try (PreparedStatement insertStmt = conn.prepareStatement(insertSql)) { insertStmt.setString(1, "Alice"); insertStmt.setInt(2, 18); insertStmt.setString(3, "Female"); insertStmt.setString(4, "Class A"); insertStmt.executeUpdate(); } // 更新数据 String updateSql = "UPDATE students SET age = ? WHERE name = ?"; try (PreparedStatement updateStmt = conn.prepareStatement(updateSql)) { updateStmt.setInt(1, 20); updateStmt.setString(2, "Alice"); updateStmt.executeUpdate(); } // 删除数据 String deleteSql = "DELETE FROM students WHERE name = ?"; try (PreparedStatement deleteStmt = conn.prepareStatement(deleteSql)) { deleteStmt.setString(1, "Alice"); deleteStmt.executeUpdate(); } // 查询数据 String selectSql = "SELECT * FROM students"; try (PreparedStatement selectStmt = conn.prepareStatement(selectSql); ResultSet rs = selectStmt.executeQuery()) { while (rs.next()) { String name = rs.getString("name"); int age = rs.getInt("age"); String gender = rs.getString("gender"); String className = rs.getString("class"); System.out.println(name + " - " + age + " - " + gender + " - " + className); } } } catch (SQLException e) { e.printStackTrace(); } } }标签:try,insertStmt,String,rs,2024,import,name From: https://www.cnblogs.com/drz1145141919810/p/18253411