如何使用Java将值插入SQL

如何使用Java将值插入SQL

对不起,如果我的问题相同。我试图查找在线文档,但仍然没有解决问题。 “ stmt.executeUpdate();”行中有错误

public class DBConnect {
    private List<SinhVien> result = new ArrayList<SinhVien>();
public void updateSQL(String masv, String malop, String ten,
            Date ngaysinh, String diachi) {
    try{
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection connection = DriverManager.getConnection("jdbc:sqlserver://MyPC:1433;databasename=QLSV;username=sa;password=APASSWORD");
            PreparedStatement stmt = connection.prepareStatement("INSERT INTO SinhVien(masv, malop, ten, ngaysinh, diachi) VALUES(?, ?, ?, ?, ?");
            stmt.setString(1, masv);
            stmt.setString(2, malop);
            stmt.setString(3, ten);
            stmt.setDate(4, ngaysinh);
            stmt.setString(5, diachi);
            stmt.executeUpdate();
    }
    catch(Exception e){
        e.printStackTrace();
    }
    }
    public static void main(String[] args) {
        DBConnect dbConnect = new DBConnect();
        dbConnect.XuatDSSV();
        dbConnect.findSinhvienById("51003146");
        dbConnect.updateSQL("123", "malop", "ten", null, "diachi");

    }

最佳答案

我建议您将查询存储在字符串中。那样会更容易阅读和发现问题...

final String query = "INSERT INTO SinhVien"
    + "(masv, malop, ten, ngaysinh, diachi) "
    + "VALUES(?, ?, ?, ?, ?)"; // <-- You were missing the close paren.
PreparedStatement stmt = connection.prepareStatement(query);

关于java - 如何使用Java将值插入SQL Server?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20767670/

10-11 22:14