Connection con = null;
Statement stmt = null;
int row = 0;
//获取GUI信息
String stuID = stuIDTextField.getText();
String stuName = stuNameTextField.getText();
String stuDepart = (String) departComboBox.getSelectedItem();
String stuClass = (String) classComboBox.getSelectedItem();
//检测
if (stuID.equals("") || stuName.equals("")) {
JOptionPane.showMessageDialog(this, "请填写完整");
return;
} else {
try {
//注册直连驱动
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
//建立连接
String url="jdbc:microsoft:sqlserver://localhost:1433;databasename=JDBC_STU";
con = DriverManager.getConnection(url,"sa","sql2008");
//创建执行语句,拼接字符串
String insertsql = "insert into studentinfo values('" + stuID + "','" + stuName + "','" + stuDepart + "','" + stuClass + "')";
stmt = con.createStatement();
注意:驱动的加载和jar包的导入
//发送sql语句
row = stmt.executeUpdate(insertsql);
if (row != 0) {
JOptionPane.showMessageDialog(this, "添加成功");
stuIDTextField.setText("");
stuNameTextField.setText("");
} catch(SQLException ex){
JOptionPane.showMessageDialog(this, "添加失败");
stuIDTextField.setText("");
stuNameTextField.setText("");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
con.close();//关闭连接
} catch (Exception ex) {
ex.printStackTrace();
}
}
}