我使用的是Java netbeans和mysql。我想检查用户在文本字段tf中输入的值是否已经存在于mysql表中。
String query1="SELECT * FROM trytable WHERE name='8'";
ResultSet rs=stmt.executeQuery(query1);
if(rs.isBeforeFirst()==true){JOptionPane.showMessageDialog(null,"already");}在上面代替8的代码中,我想给出用户在表单中输入的值,然后检查该值在表单中是否已经存在。
请帮我排在第一行。谢谢
发布于 2018-07-29 23:38:39
这是最终的代码,将会工作得非常好。
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query = "SELECT * FROM table_name WHERE name=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1,jtf.getText());
ResultSet rs = preparedStatement.executeQuery();
if(rs.next()==true){
JOptionPane.showMessageDialog(null,"Value already exist");
}
else{
JOptionPane.showMessageDialog(null,"Value not present");
String query1="INSERT INTO table_name(col_name) VALUES (?)";
preparedStatement = conn.prepareStatement(query1);
preparedStatement.setString(1,jtf.getText());
preparedStatement.execute();
JOptionPane.showMessageDialog(null,"DONE");
}
rs.close();
preparedStatement.close();
}
catch(Exception e){
System.out.println("Exception:"+e.getMessage());
}https://stackoverflow.com/questions/51577297
复制相似问题