I have created a JList by taking inputs from user in jtextField. Then I have saved the jList to Mysql database by converting the JList to String as I want to save the JList item in a single row as single entry.
code for adding user input to jList:
DefaultListModel dlm= new DefaultListModel();
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String userInput= jTextField2.getText();
dlm.addElement(userInput);
jList1.setModel(dlm);
jTextField2.setText(null);
}
Code Used for saving the JList into MySQL database as String:
String allitem=null;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
for(int i = 0;i<jList1.getModel().getSize();i++)
{
allitem = (String)jList1.getModel().getElementAt(i)+"::"+allitem;
}
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ft", "root", "");
PreparedStatement stmt = conn.prepareStatement("insert into ftt (listname,listitem) values (?,?)");
stmt.setString(1, jTextField1.getText());
stmt.setString(2, allitem);
stmt.execute();
conn.close();
}catch(
Exception e)
{
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
JOptionPane.showMessageDialog(null, "done");
}
Now in the next page user can view all the Strings (Jlist is saved as String) item in the JList. I wan to disaplay user the details of the JList item selected. I have created a Jtable and want to display the other details of the JList item selected.
Code I have Tried:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
Update_table1();
}
private void Update_table1(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/ft","root","");
String query="SELECT listname FROM ftt WHERE listitem=?;";
PreparedStatement prepstmt=conn.prepareStatement(query);
String s = (String) jList1.getSelectedValue();
prepstmt.setString(1,s);
ResultSet rs=prepstmt.executeQuery();
jTable3.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
But when using this code the Jtable is not showing any value although it is taking the table header name. Please can anyone check I correct in how to search in the String saved in MySQL database. I think the problem is there as other things are working fine.
note: Its not showing any error or exception.
It is not the best way to keep record as the way you are doing as concatenated string. You better use a normalized table and keep all list elements as a record. For your code you are trying to query on a field which contain concatenated information. So you may use "like" keyword instead of "=".
"SELECT listname FROM ftt WHERE listitem like %?%;"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.