输入一个人的姓名,进行查询,查询出这个学生的信息,进行身高、体重等修改,点击修改按钮,把界面上的内容修改到数据库中。
修改前
修改后
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//判断一下用户是不是先进行查询了
String name1 = textname.getText().trim();
String age1 = textage.getText().trim();
String tall1 = texttall.getText().trim();
String weight1 = textweight.getText().trim();
String address1 = textaddress.getText();
String school1 = (String)combo1.getSelectedItem();
String depart1 = (String)list1.getSelectedValue();
//定义数据库联接的驱动程序
String driver = "org.gjt.mm.mysql.Driver";
//定义MySQL数据库的联接地址
String url = "jdbc:mysql://localhost:3306/sias2?characterEncoding=UTF8";
//声明联接类
Connection conn = null;
try{
//使用JDBC技术创建数据库联接
Class.forName(driver);
//使用DriverManager类的getConnection()方法建立联接,第一个字符参数定义用户名,
//第二个字符参数定义密码
conn = DriverManager.getConnection(url, "root", "111222");
if(conn != null){
System.out.println("成功联接JDBC数据源.");
}
//定义一个修改语句,更新学生表,设置年龄等于什么,体重等于什么等等,最后是一个where子句
String sql1 = "update student set name ='"+name1+"', age="+age1+",tall="+tall1+",weight="+weight1+",address='"+address1+"',school='"+school1+"',depart='"+depart1+"' where name = '"+name1+"'";
//输出语句对上面的修改语句进行测试
System.out.println(sql1);
Statement stmt = conn.createStatement();
int a = stmt.executeUpdate(sql1);
if(a == 1){
System.out.println("更新成功!");
}
}catch(Exception ex){
ex.printStackTrace();
}
try{
//关闭数据库联接类
conn.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
);
点击取消按钮清空界面信息
完成图
为取消按钮添加控件
//清空操作
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textname.setText("");
textage.setText("");
texttall.setText("");
textweight.setText("");
textaddress.setText("");
combo1.setSelectedIndex(0);
list1.setSelectedValue("多媒体", true);
}
});