every row from the database being one JList item? - java

I currently have a database that is working well. It displays the text from each column of the database into 5 labels on the app user interface. Some of the time, depending on what the user enters, I want it to display a list of rows from the database, I was thinking of using the JList.
the current code to display to the labels is:
String sqlQuery = "select Column1, Column2, Column3, Column4, Column5 from APP.DATA123 " +
"where (Column1 = ?) AND (Column2 = ?) AND (Column3 = ?) OR (Column1 = ?) AND (Column2 = ?)";
String abc = jTextField2.getText();
String cba = (String)jComboBox1.getSelectedItem();
String cab = (String)jComboBox2.getSelectedItem();
String data = "jdbc:derby://localhost:1527/sample";
try (
Connection conn = DriverManager.getConnection(
data, "app", "app");
PreparedStatement st = conn.prepareStatement(sqlQuery)) {
Class.forName("org.apache.derby.jdbc.ClientDriver");
st.setString(1, abc);
st.setString(2, cba);
st.setString(3, cab);
st.setString(4, cba);
st.setString(5, cab);
ResultSet rec = st.executeQuery();
while (rec.next()) {
jLabel1.setText(rec.getString("Column1"));
jLabel2.setText(rec.getString("Column2"));
jLabel3.setText(rec.getString("Column3"));
jLabel4.setText(rec.getString("Column4"));
jLabel5.setText(rec.getString("Column5"));
}
st.close();
Is there an easier way to make it so that if there is more than one row of the database to be displayed to the user, I can make a JList so that all of the columns of one row (and possibly an image but I'll think about that later), are displayed as one item on the JList. So Columns1-5 are one JlistItem, and then columns 1-5 for the next database row are the next JList item etc?
Or another similar way that anyone knows of?
There is not that much text per column only about 5-15 characters.

You have to bind your JList to a ListModel implementation and fill that ListModel. In your case - each item in your ListModel is a concatenated string of all items from each row in ResultSet. Something like following :
DefaultListModel<String> model = new DefaultListModel<>();
JList list = new JList(model);
JScrollPane pane = new JScrollPane(list);//add the "pane" to your form next line
String abc = jTextField2.getText();
String cba = (String) jComboBox1.getSelectedItem();
String cab = (String) jComboBox2.getSelectedItem();
String data = "jdbc:derby://localhost:1527/sample";
try(
Connection conn = DriverManager.getConnection(
data, "app", "app");
PreparedStatement st = conn.prepareStatement(sqlQuery))
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
st.setString(1, "abc");
st.setString(2, "cba");
st.setString(3, "cab");
st.setString(4, "cba");
st.setString(5, "cab");
ResultSet rec = st.executeQuery();
// may want to make it constant (final static)
final String SPACE = " ";
StringBuilder sBuilder = new StringBuilder();
while (rec.next()) {
sBuilder.setLength(0);
sBuilder
.append(rec.getString("Column1")).append(SPACE)
.append(rec.getString("Column2")).append(SPACE)
.append(rec.getString("Column3")).append(SPACE)
.append(rec.getString("Column4")).append(SPACE)
.append(rec.getString("Column5")).append(SPACE);
model.addElement(sBuilder.toString());
}
st.close();
Take a look at this article, might be very helpful in your case. And, BTW, googling or reading docs is much faster than writing a question on SO and waiting for answer =). Cheers.

Related

How do I retrieve a single cell from MySQL database using query and assigned it to a variable in Java Netbeans Apache

First I am going to try using query to retrieve the int min_stock single cell using the item description. Then put that value into a variable. I want to be able to have the variable minStock to be equal to a number. I want to use it to make operations in my program.
PreparedStatement cm = con.prepareStatement(checkMinimumStock);
ResultSet minS = cm.executeQuery("SELECT min_stock FROM items WHERE item_description = '"+item+"'");
int minStock = minS.getInt("min_stock");```
you are choose wrong way to use PrepareStatment.
you have two option to do :
1:
String sql = "SELECT min_stock FROM items WHERE item_description = ?";
PreparedStatement cm = con.prepareStatement(sql);
cm.setString(1, item);
ResultSet rs = cm.executeQuery();
2:
String sql = "SELECT min_stock FROM items WHERE item_description = '" + item + "'";
ResultSet rs = con.createStatement().executeQuery(sql);
and then
if (rs.next())
int minStock = rs.getInt("min_stock");
else
//not found any match row in DB table
Try this
String checkMinimumStock = "SELECT min_stock FROM items WHERE item_description = ? ";
PreparedStatement cm = con.prepareStatement(checkMinimumStock);
cm.setString(1,item);
ResultSet minS = cm.executeQuery();
if(minS.next()){
int minStock = rs.getInt("min_stock");
}
String checkMinimumStock = "SELECT min_stock FROM items WHERE item_description = ? ";
Forgot to add this in the beginning of the code!

Mysql : Query with LIKE on varbinary column from java

Lets say I have this table:
CREATE TABLE T (col varbinary(100));
Now I would like to do a "LIKE" query on this column using java, something like this -
String query="SELECT * from T WHERE col LIKE ?";
PreparedStatement st = connection.prepareStatement(query); // Assuming I already have connection object
byte[] prefixBytes = somePrefixBytesIWouldLikeToSearchFor;
String likeString = new String(bytes) + "%";
st.setString(1, likeString);
st.executeQuery();
Is that right way to go about it? If not, what is the correct way. Thanks.
You could use string concat inside sql command eg:
String query="SELECT * from T WHERE col LIKE concat(?, '%')";
PreparedStatement st = connection.prepareStatement(query); // Assuming I already have connection object
byte[] prefixBytes = somePrefixBytesIWouldLikeToSearchFor;
String likeString = new String(bytes)
st.setBytes(1, bytes);
st.executeQuery();

Getting next value from sequence

I have a bit of code here to get the next value of my sequence, but it is adding the total number of records onto the result each time.
I'm only learning about prepared Statements, I'm thinking this is something small, maybe rset.next() should be something else?
public void add( String title, String actor, String genre ) {
try {
String sql2 = "Select movie_seq.nextval from Movie";
pstmt = conn.prepareStatement(sql2);
rset = pstmt.executeQuery();
int nextVal = 0;
if(rset.next())
nextVal = rset.getInt(1);
String queryString = "Select MovieID, Title, Actor, Genre from Movie";
pstmt = conn
.prepareStatement(queryString,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rset = pstmt.executeQuery();
rset.moveToInsertRow();
rset.updateInt(1, nextVal);
rset.updateString(2, title);
rset.updateString(3, actor);
rset.updateString(4, genre);
rset.insertRow();
pstmt.executeUpdate();
} catch (SQLException e2) {
System.out.println("Error going to previous row");
System.exit(1);
}
}
Any help appreciated.
I think you don't need the call to pstmt.executeUpdate();
As stated in ResultSet doc, the function insertRow stores the row in the Dataset AND in the database.
The following code shows all that's necessary to add a new row:
rset.moveToInsertRow(); // moves cursor to the insert row
rset.updateString(1, "AINSWORTH"); // updates the
// first column of the insert row to be AINSWORTH
rset.updateInt(2,35); // updates the second column to be 35
rset.updateBoolean(3, true); // updates the third column to true
rset.insertRow();
rset.moveToCurrentRow();
Why dont you iterate using while rather than if . something like this
List lst = new ArrayList();
Someclass sc = new SomeClass(); //object of the class
String query = "SELECT * from SomeTable";
PreparedStatement pstmt = sqlConn.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
Role role = null;
while (rs.next()) {
String one = rs.getString(1);
String two = rs.getString(2);
boolean three = rs.getBoolean(3);
//if you have setters getters for them
sc.setOne(one);
sc.setTwo(two);
sc,setThree(three);
lst.add(sc)
}
//in the end return lst which is of type List<SomeClass>
}
Shouldn't you be doing this instead?:
String sql2 = "Select " + movie_seq.nextval + " from Movie";
As it is, it seems like you're passing a slightly bogus string into the SQL query, which is probably defaulting to the max index (not 100% positive on that). Then rs.next() is just incrementing that.

Deleting selected row in MySQL database through JTable

tb_records = jtable name
records = table name inside my database
Date = my first column
hey = substitute for my real password
mydatabase = name of my database
My problem is that, when I highlight a row in my JTable and delete it, it deletes all the rows. I want to delete the selected row only. Here's my code:
int row = tb_records.getSelectedRow();
DefaultTableModel model= (DefaultTableModel)tb_records.getModel();
String selected = model.getValueAt(row, 0).toString();
if (row >= 0) {
model.removeRow(row);
try {
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "hey");
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
ps.executeUpdate();
}
catch (Exception w) {
JOptionPane.showMessageDialog(this, "Connection Error!");
}
}
What could be the problem here? How can I delete a selected row in my database and not all the rows?
DefaultTableModel model = (DefaultTableModel) jTable.getModel();
int row = jTable.getSelectedRow();
String eve = jTable.getModel().getValueAt(row, 0).
String delRow = "delete from user where id="+eve;
try {
ps = myCon.getConnection().prepareStatement(delRow);
ps.execute();
JOptionPane.showMessageDialog(null, "Congratulation !!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
1) Don't display your own message. Display the error message from the Exception as it will give a better explanation what the problem is.
2) Use a proper PreparedStatement for the SQL. You are less likely to make syntax errors. Something like:
String sql = "delete from records where Date= ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, selected );
stmt.executeUpdate();
I don't know much about SQL but maybe you need to pass a Date object not a String object since your where clause is using a Date?
The OP wrote:
SOLUTION: Pick a column with unique values. My Date column has the same values that's why it's deleting all my rows even though I set my row as getSelectedRow. Time_in = my 4th column with unique values.
change
String selected = model.getValueAt(row, 0).toString();
to
String selected = model.getValueAt(row, 3).toString();
and
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
to
PreparedStatement ps = conn.prepareStatement("delete from records where Time_in='"+selected+"' ");

Java PreparedStatement Wilcard doesn't work

I have DDBB with a table users and I'm trying to get fields user_id and user_pass by searching for user_name.
So, when I run the following query:
SELECT `user_id`, `user_pass` FROM `users` WHERE `user_name` LIKE '%aName%';
It returns, ie aName = "John":
+---------+-----------+
| user_id | user_pass |
+---------+-----------+
| 5 | "1234" |
+---------+-----------+
Ok, then I want to perform this using a PreparedStatement, for that reason I have made this function:
private final String QUERY_GETUSERNAME2 =
"SELECT `user_id`, `user_fname`"
+ " FROM `users`"
+ " WHERE `user_fname` LIKE ?;";
private String[][] getUsersInv(String usrName){
ArrayList<String[]> alAux = new ArrayList();
String[][] ret = null;
try{
PreparedStatement st = _conn.prepareStatement(QUERY_GETUSERNAME2);
st.setString(1, "'%"+usrName+"%'");
ResultSet rs = st.executeQuery();
while(rs.next()){
String[] asAux = {String.valueOf(rs.getInt(1)), rs.getString(2)};
alAux.add(asAux);
}//while
}catch(SQLException e){
e.printStackTrace(System.out);
}finally{
if (!alAux.isEmpty()){
ret = new String[alAux.size()][alAux.get(0).length];
for (int i = 0; i < alAux.size(); i++)
ret[i] = alAux.get(i);
}//fi
}
return ret;
}
As you can see, the function returns a String[][], so I check in a previous function if returns is or not null:
public void insertUsersInvTableModel(JTable table, String user){
DefaultTableModel model = (DefaultTableModel) table.getModel();
String[][] row = getUsersInv(user);
if (row != null)
model.addRow(row);
}
And this function is call from the listener for a JButton:
private void addUserActionPerformed(java.awt.event.ActionEvent evt) {
if (comboUsers.getSelectedIndex() != 0){
new Users(_conn).insertUsersInvTableModel(_target, String.valueOf(comboUsers.getSelectedItem()));
_target.validate();
_target.repaint();
setVisible(false);
}
}
As you can imagine, there's a JDialog with a JComboBox with all the users listed down.
As table users is AUTO_INCREMENT, the user_id has some gaps (or maybe it will have), and the only way to build the JComboBox was without relate user_id to JComboBox index.
But, the problem is that whenever I pick an item from the JComboBox, and I run the process to get the user_id and user_pass based on the item selected (nor the index), the ResultSet is always NULL.
Any idea?
Thanks.
replace
st.setString(1, "'%"+usrName+"%'");
with
st.setString(1, "%"+usrName+"%");
The single quotes are automatically added by the PreparedStatement. With the Quotes the query will look for the String '%usrname%' instead of %usrname%
try
st.setString(1, "%"+usrName+"%");
instead of
st.setString(1, "'%"+usrName+"%'");
SOLUTION
As Marco Forberg pointed, quotes used for envolve the string parameter (') are not compulsory. Removing them fix the issue.

Categories