我正在使用SQL Server 2018和JDK 8.0以及NetBeans。连接到SQL Server时,出现img中所示的SQL异常 enter image description here
我正在使用以下代码:
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//Connection establishment
Connection con=DriverManager.getConnection("jdbc:sqlserver//DESKTOP-CU5U75J\\SQLSERVER1;","","");
//Statement Object
Statement st=con.createStatement();
//For DML use executeUpdate method of Statement Class
st.executeUpdate("insert into Employee (Employee_Id, Employee_Name) values ("+Integer.parseInt(idTF.getText())+","+nameTF.getText()+")");
//Commit Statement
con.commit();
JOptionPane.showMessageDialog(this, "Message", "The Data is Entered", JOptionPane.INFORMATION_MESSAGE);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
}
答案 0 :(得分:1)
您在jdbc网址中错过了冒号':'
Connection con=DriverManager.getConnection("jdbc:sqlserver://DESKTOP-CU5U75J\\SQLSERVER1;integratedSecurity=true","","");
应该是jdbc:sqlserver//DESKTOP-CU5U75J\\SQLSERVER1;
的是jdbc:sqlserver://DESKTOP-CU5U75J\\SQLSERVER1;
此外,我建议您使用PreparedStatement
插入您的记录。
String sql="insert into Employee (Employee_Id, Employee_Name) values (?,?)";
PreparedStatement stmt=con.prepareStatement(sql);
stmt.setInt(1, Integer.parseInt(idTF.getText()));
stmt.setString(2, nameTF.getText());
stmt.executeUpdate();