日期:2014-05-20 浏览次数:21069 次
private MySql ms = new MySql();
//省略部分无关代码
btnSave.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String sql = "INSERT INTO student VALUES("+txtId.getText()+",'"+txtName.getText()+"');";
ms.ExecuteSql(sql);
ms.closeConnection();
showStu();
}
});
public class MySql {
private Connection conn =null;
private final String DB_DRIVER="com.mysql.jdbc.Driver";
private final String DB_URL="jdbc:mysql://localhost:3306/school";
private final String DB_USER="root";
private final String DB_PWD="root";
public MySql(){}
public void getConnection(){
try {
Class.forName(DB_DRIVER);
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PWD);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeConnection(){
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean ExecuteSql(String sql){
int rt=0;
if(conn==null){
getConnection();
}
try {
Statement stm = conn.createStatement();
stm.executeUpdate(sql);
//stm.close();
//不管有没有这个close都会有异常
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(rt==0){
return false;
}else{
return true;
}
}