简体   繁体   中英

how insert value into sql sever using java?

sorry if my questions are identical. I was trying to find out online documentation but I still have not solved the problem. it's an error in the line "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");

    }

I suggest you store your query in a String. It would have been easier to read, and find the problem...

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

Try to add connection.commit() after stmt.executeUpdate(). And please, post the exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM