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 %?%;"
Related
I have a problem with JComboBox. It's blocking another field in a frame meant to display another value that is linked through a foreign key in a database, a value that depends on the combo box already pop out. But somehow, after the user clicks the combo box it is blocking another field. The app is using MySql.
Here's the code:
ComboBox method to fill value from DB
public void comboBoxBerat(){
DbConnection DB = new DbConnection();
DB.DbConnection();
con = DB.con;
stat = DB.stmt;
try {
sql = "SELECT * FROM weight_of_services";
rs = stat.executeQuery(sql);
while (rs.next()) {
jComboBoxBerat.addItem(rs.getString("weight"));
}
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
Action when selection is made from combo box, its get the value that linked with foreign key
private void jComboBoxBeratActionPerformed(java.awt.event.ActionEvent evt) {
DbConnection DB = new DbConnection();
DB.DbConnection();
con = DB.con;
stat = DB.stmt;
String item = (String)jComboBoxBerat.getSelectedItem();
String sql = "SELECT price FROM weight_of_services WHERE weight = ?";
try {
pst = con.prepareStatement(sql);
pst.setString(1, item);
rs = pst.executeQuery();
if (rs.next()) {
String price = rs.getString("price");
txtHargaBerat.setText(price); //put value from combobox to txtField
}
con.close();
} catch (Exception e) {
}
}
The problem after I select from the box its blocking another field.
This is the combo box problem in the frame
It's solved. This because i am using jpanel for customizing color for the frame. Its just so messed up with the stacking one panel on top of the other one. That's why my dropdown list get blocked. So what I did, removed all the panel. Custom and sorting it more carefully and tidy from the start.
I'm trying to display database item into a JComboBox and this is my code.
public static void checkItemName(){
Connection conn = SQLite.SQLite();
String sql = "select itemname from item";
try{
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
String list = resultSet.getString("itemname");
purcItemName.addItem(list);
conn.close();
}
} catch (SQLException lol){
System.out.println(lol.toString());
}
}
I did declare static JComboBox purcItemName; and purcItemName = new JComboBox();
The method/function will be called then user press login button.
The problem I'm having now is that, it only shows one item while my database has multiple items.
Anyone got an idea why?
Vector v = new Vector();
while (resultSet.next()){
String list = resultSet.getString("itemname");
v.add(list);
}
conn.close();
purcItemName.setModel(new DefaultComboBoxModel(v));
store the data you got from database in a vector object and once that is completed set the vector object in your combobox as a new model. try this one
and don't close the connection inside your loop.
you are closing connection inside resultSet.next() check, put the conn.close() outside, to the end
Im trying to insert data from jtable to database!! the first three columns(stafftimetableid,staffname,staffid) are inserted from the jtexfield(no errors found,successfully added) but when im trying to insert from jtable it promts a java.null pointerExcetion error !!
I have no errors in database connection !!
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jComboBox1.getSelectedItem().equals("Staff Time Table"))
{
try
{
PreparedStatement pst =null;
Connection con = clerkpanell.DBConnection.connectDB();
String data=jTable2.getValueAt(0,1).toString();
String sql = "insert into stafftimetable (StaffTimeTableID,StaffName,StaffID,7.50-8.30) values ('"+ttid.getText()+"','"+staffname.getText()+"','"+staffid.getText()+"','"+data+"');";
pst=con.prepareStatement(sql);
pst.executeUpdate();
// JOptionPane.showMessageDialog(null,"Added");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
}
In this statement String sql = "insert into stafftimetable (StaffTimeTableID,StaffName,StaffID,7.50-8.30) values ('"+ttid.getText()+"','"+staffname.getText()+"','"+staffid.getText()+"','"+data+"');";
Please store the ttid.getText(), staffname.getText(),staffid.getText()into separate variables. Something like this,
String ttid=ttid.getText();
String staffname = staffname.getText();
String staffid = staffid.getText();
and then the insert statement should be something like this
String sql = "insert into stafftimetable (StaffTimeTableID,StaffName,StaffID,7.50-8.30) values ('"+ttid.+"','"+staffname+"','"+staffid+"','"+data+"');";
Ok So I have a program where I add new Players to a database, and where I load them users into a list. The problem is when I delete a user, then go to add a new user the new player gets added in to where the old user was. Basically because that spot is free now and I use:
rs.moveToInsertRow();
is there a way that when adding a new player it 'Always' adds to the end of the the database. Like when you delete a row from table to make the database compress so it has no gaps?
here is the code:
public static void Save() { try {
String Name = "#####";
String Pass= "#####";
String Host = "######";
Connection con = DriverManager.getConnection(String.format(
"jdbc:mysql://%s:%s/%s", Host, "####", "####"),
Name, Pass);
Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM Accounts";
ResultSet rs = stmt.executeQuery(sql);
rs.moveToInsertRow( );
String userName= TestForm.UsernameTextField.getText(); //make this equal to whats in textfield
String password= TestForm.PasswordTextField.getText(); //make this equal to whats in textfield
String insertQuery="insert into Accounts (`Username`,`Password`) values ('"+userName+"','"+password+"');";
stmt.executeUpdate(insertQuery);
stmt.close();
rs.close();
}
catch(Exception e)
{
System.out.println("ERROR");
e.printStackTrace();
}
What's your table create statement? SHOW CREATE TABLE Accounts ;
Seems like an AUTO_INCREMENT integer primary key in the table would help your issue.
I am trying to capture & store user details(name, password etc) & store them in sql database so as to be used by users to login in future.
How do I save the details as a row in the database, yet they are entered as individual strings?
Also, how do I capture &store details like gender(Male,Female) selected from a Combobox? Thanks.
private class achandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
//capture user details
String fnamevalue = fnametext.getText();
String lnamevalue = lnametext.getText();
String usernamevalue = usernametext.getText();
char[] pwdvalue = pwdtext.getPassword();
char[] pwdrptvalue = pwdrpttext.getPassword();
if(pwdvalue == pwdrptvalue) {
//add user details to an array
String[] userdetail = {fnamevalue, lnamevalue, usernamevalue, pwdvalue.toString()};
try {
Class.forName("com.mysql.jdbc.Driver");
String Url = "jdbc:mysql://localhost/nsibirwa?" +
"user=root&password=1234";
Connection con = DriverManager.getConnection(Url);
Statement stmt = con.createStatement();
//I am stuck here!!!! i.e. adding 'userdetail' as a tuple in the database
}
catch (SQLException e) {
System.out.println("SQL Exception: "+ e.toString());
}
catch (ClassNotFoundException cE) {
System.out.println("Class Not Found Exception: "+ cE.toString());
}
}
else {
JOptionPane.showMessageDialog(null, "password not matching!",
"Password error", JOptionPane.ERROR_MESSAGE);
}
}
}
adding 'userdetail' as a tuple in the database
Something like:
Connection con = DriverManager.getConnection(Url);
PreparedStatement stmt = con.prepareStatement("insert into user_details (fname, lname, username, pwd) values (?,?,?,?));
stmt.setString(1, fnamevalue);
stmt.setString(2, lnamevalue);
stmt.setString(3, username);
stmt.setString(4, new String (pwdvalue));
stmt.executeUpdate();
Your code has another problem:
if (pwdvalue == pwdrptvalue)
you can not compare objects like that. You need to convert those char[] to Strings and use equals() to compare them. Search for "java string equals" to find out why. This is very basic Java knowledge (and is covered in each and every tutorial I have seen)
This assumes you have a table named user_details with the columns fname, lname, username and pwd. If your table definition is different you need to adjust the insert statement.
Also, how do I capture &store details like gender(Male,Female) selected from a Combobox?
I would suggest you open a second question for that. You should not mix completely different topics (JDBC/SQL vs. plain Swing) in a single question.