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("sun.jdbc.odbc.JdbcOdbcDriver");
//建立与数据源的连接
con = DriverManager.getConnection("jdbc:odbc:studentodbc", "sa", "sql2008");
//创建执行语句,拼接字符串
String insertsql = "insert studentinfo values('" + stuID + "','" + stuName + "','" + stuDepart + "','" + stuClass + "')";
System.out.println(insertsql);
stmt = con.createStatement();
//发送sql语句
row = stmt.executeUpdate(insertsql);
if (row != 0) {
JOptionPane.showMessageDialog(this, "添加成功");
stuIDTextField.setText("");
stuNameTextField.setText("");
} else {
JOptionPane.showMessageDialog(this, "添加失败");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
con.close();//关闭连接
} catch (Exception ex) {
ex.printStackTrace();
}
}
}注意:驱动的加载和数据库的操作