如何使用java将值插入sql server?

时间:2013-12-24 23:15:30

标签: 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");

    }

2 个答案:

答案 0 :(得分:1)

我建议您将查询存储在String中。它会更容易阅读,并找到问题......

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

答案 1 :(得分:1)

尝试在stmt.executeUpdate()之后添加connection.commit()。请发布例外。