JPasswordField类继承自JTextField
在调用JPasswordField.getText()方法时会出现报警
(我试验过,代码可以正常运行,但不建议这样写)
JPasswordField中有获取文本的方法JPasswordField.getPassword()
但是返回的结果是char型
解决办法为:
String password=new String(JPasswordField.getPassword());
这样就转变为String型了
例子:
public static String addStudent(Student student) {
Connection con=null;
Statement stat=null;
Statement stat1=null;
ResultSet rs=null;
try {
//建立数据库连接
String password=new String(StudentInitialization.t2.getPassword());
con=StudentListener.getConnection2(StudentInitialization.t1.getText(),password);
stat=(Statement) con.createStatement();
stat1=(Statement) con.createStatement();
String sql1="select * from student";
rs=stat1.executeQuery(sql1);
while(rs.next()) {
//学号重复
if(rs.getString("sno").equals(student.getId())){
return "学号重复!:"+student.getId();
}
}
String sql="insert into student values('"+student.getId()+"','"+student.getName()+"','"+student.getSex()+"','"
+student.getBirthday()+"','"+student.getPhone()+"','"+student.getDorm()+"')";
//执行语句
stat.executeUpdate(sql);
}catch(SQLException e) {
//关闭对象
e.printStackTrace();
}finally {
try {
if(stat!=null)
stat.close();
if(con!=null)
con.close();
}catch(SQLException ex) {
ex.printStackTrace();
}
}
return "学生信息已插入!!!";
}
例子中的StudentInitialization.t2就是我定义的一个static JPasswordField类型