- 增加button6按钮
- 为按钮增加监听器以及相应的功能
gbc.gridy = 5;
gbc.gridx = 3;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 1;
gbc.weighty = 1;
gb2.setConstraints(button6, gbc);
c3.add(button6);//删除
button6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name1 = textname.getText().trim();
//定义数据库联接的驱动程序
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", "1122");
if(conn != null){
System.out.println("成功联接JDBC数据源.");
}
Statement stmt = conn.createStatement();
String sql1 = "delete from student where name = '"+name1+"' ";
System.out.println(sql1);
int a = stmt.executeUpdate(sql1);
if(a == 1) {
System.out.println("删除成功");
JOptionPane.showMessageDialog(null,"删除成功");
}
}catch(Exception ex){
ex.printStackTrace();
}
try{
//关闭数据库联接类
conn.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
});
总计
//原来的代码
//定义MySQL数据库的联接地址
String url = "jdbc:mysql://localhost:3306/sias1?user='root';password='root'";
//更新过后的代码
String url = "jdbc:mysql://localhost:3306/sias2?characterEncoding=UTF8";
数据库功能相关代码都是复制粘贴老师给的代码,没有自己敲过
本次距离上次复制粘贴老师代码已经过了很久了,代码有点瑕疵需要更改也忘了。
经过本次实验加深了记忆,以及纠错能力。
- 连接数据库sias2,后面增加characterEncoding=UTF8,可以显示字符集
- 在没有更改之前无法查询出带有汉字的人名。
错误2
3. 在增加删除语句数据库查询,报错
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘delect from student where name = ‘22’’ at line 1
- 对于此报错严格核对纠正了好几次都没有发现错误
- 错误原因,delete敲成delect