Looping in mysql java - searching templates - java

I have a table in mysql that contain a field called template.
I have one template stored in a variable, I need to compare that variable with each of the other templates found in the table until a match is found. I dont know how to retrieve one template from the database row at a time, compare it and if it does not match, move to next row to compare again and so on until match is found. I am new to mysql looping, please help.
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "");
PreparedStatement st;
st = con.prepareStatement("select template from tbl1 ");
ResultSet result = st.executeQuery();
while (result.next()) {
String dbTemplate = result.getString("template");
if x == dbtemplate
} else {// move to next row? How to say do the loop for next row in table??
}

Ask SQL to check it for you, Try this:
st = con.prepareStatement("select template from tbl1 where template = ?");
st.setString(1, "template_name");
Then you would only have results that templates matches

result.next() any way gets next row. All you need to do would do condition check inside and if condition satisfied, then only execute the functionality you want.
while (result.next()) {
if(yourConditionSatisfied) {
//All your logic goes here. If you want to break the lookup, just add break here.
}
}

Related

How to parse values for the result set's .equals function?

image showing my jFrame
I am making a frame which shows records in the sql table one-by-one using text fields as shown. While writing the code for the next button, I need to know the position of the result set to go to the next record. For this purpose, I used a do-while loop with an "if" condition. Following is my code:
try{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String url="jdbc:mysql://localhost/MYORG", userid="root", pwd="shreyansh";
conn=DriverManager.getConnection(url,userid,pwd);
stmt=conn.createStatement();
String query="select * from emp;";
rs=stmt.executeQuery(query);
String search=jTextField1.getText();
String search1=jTextField2.getText();
double search2=Double.parseDouble(jTextField3.getText());
String search3=jTextField3.getText();
rs.first();
do{
if(rs.equals(new Object[] {search, search1, search2, search3}))
break;
}while(rs.next());
rs.next();
String nm=rs.getString("Name");
String desg=rs.getString("Designation");
double pay=rs.getDouble("Pay");
String city=rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(pay + "");
jTextField4.setText(city);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
But it shows an error "after end of Result Set".
Please help me with this.
Any suggestions to make my code better are also welcome.
Thanks in Advance!!
You can't use ResultSet.equals for this, because that is not what the Object.equals contract is for. It is for checking if an object is equal to another object of the same (or at least compatible) type. A ResultSet will therefor never be equal to an array of object values.
It looks like you want to select a single row from the emp table that matches your search values, in that case the correct solution is to ask the database for only that row. Selecting all rows and then filtering in your Java application is very inefficient, because the database has to send all rows to your application, while finding data is exactly what a database is good at.
Instead, you should use a where clause with a prepared statement:
try (Connection connection = DriverManager.getConnection(url, userid, pwd);
PreparedStatement pstmt = connection.prepareStatement(
"select * from emp where Name = ? and Designation = ? and Pay = ? and City = ?")) {
pstmt.setString(1, search);
pstmt.setString(2, search1);
pstmt.setDouble(3, search2);
pstmt.setString(4, search3);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next() {
String nm = rs.getString("Name");
String desg = rs.getString("Designation");
double pay = rs.getDouble("Pay");
String city = rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(String.valueOf(pay));
jTextField4.setText(city);
} else {
// handle not found case
}
}
}

Get the data from mysql rows and display them separately by the ResultSet in Java

I have a mysql table user which is consisted of id, name, password and email columns.
Is there a way to create some sort of query or java code that will print in my message dialog window all of the users names.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
String sql = "select * from user;";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
if (rs.next()) {
val1 = rs.getString(2);
val2 = rs.getString(3);
}
value = val1 + " " + val2;
JOptionPane.showMessageDialog(null,value);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
}
This only prints the name and the surname of the first user from the table :(
I want to print them all one below another!
If I set rs.getString(5); - it gives me an error: column index out of range.
I suggest you avoid JOptionPane for this kind of code. Better to use some Frame (Swing) and display all of the users into a separate window.
The problem with your code is that variable value is lyiong outside of the loop (which must be btw while loop, as spencer said).
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
String sql = "select * from user;";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
val = rs.getString(2) + " " + rs.getString(3);
value += val + " ";
}
JOptionPane.showMessageDialog(null,value);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
}
Try to avoid this type of code, use ArrayList and save in the array all of the users credentials. Then easily label it wherever you want.
You're only fetching the first row from the resultset. It sounds like you want a loop, and process every row from the resultset.
while (rs.next()) {
}
UPDATE
Q: It only gives me now the last user. Probably because it overwrites the val1 and val2 variable. I suppose somehow this should also goes into the loop..
A: Yes, it should go inside the loop. But I'd be populating a collection, rather than concatenating a String.
As a performance and maintenance note, you can avoid the messiness of the string concatenation in the Java by doing the concatenation in the SQL statement. I wouldn't use SELECT * and rely on the positions of two particular columns in the resultset.
I'd use a SQL statement like this:
SELECT CONCAT(u.first_name,' ',u.last_name) AS user_name FROM users
If I wasn't populating a collection, and I needed to concatenate a honkous string, I'd use a StringBuffer, e.g.
val = new StringBuffer(4096));
while (rs.next()) {
val.append(rs.getString("user_name"));
}
value = val.toString;

How to delete all rows in database on one click

I have a two database table, on a single button click in my program , I want to delete all the two table's data. But there's always one datum left on the table.. Here is my code:
public void mouseClicked(MouseEvent arg0) {
int confirm = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete the log? ", "Log", JOptionPane.YES_NO_OPTION );
if (confirm == JOptionPane.YES_OPTION){
try{
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:RIM");
Statement st1 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
Statement st2 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql1 = "select * from userLogIn";
ResultSet rs1 = st1.executeQuery(sql1);
String sql2 = "select * from userViewed";
ResultSet rs2 = st2.executeQuery(sql2);
while(rs1.next()){
rs1.deleteRow();
rs1.first();
}
while(rs2.next()){
rs2.deleteRow();
rs2.first();
}
editorPane.setText("");
}catch(Exception e){e.printStackTrace();}
When there is only one element left, your call to first() sets the cursor to that element, but then the next() call in the while condition will return false, causing the exit from the loop and thus the deleteRow won't be executed.
Use rs.beforeFirst()`.
Note that your code has lots of issues, so get this answers as "for educational purposes" only.
Why are you iterating over a select record set at all? It's incredibly inefficient.
If you want to delete all data from those tables, you can simply execute the statements:
delete from userLogin;
delete from userViewed;
(or use truncate).

JAVA: get cell from table of mysql

I get a parameter is called 'id' in my function and want to print the cell of the name of this id row.
for example:
this is my table:
id name email
1 alon alon#gmail.com
I send to my function: func(1), so I want it to print 'alon'.
this is what I tried:
static final String url = "jdbc:mysql://localhost:3306/database_alon";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "Admin");
String query_txt = "SELECT * FROM authors WHERE id = " + id;
Statement ps2 = con.createStatement();
ResultSet my_rs = ps2.executeQuery(query_txt);
System.out.println(my_rs.getString("name"));
con.close;
Everything is fine, but just one problem. You need to move your ResultSet cursor to the first row before fetching any values: -
Use: -
ResultSet my_rs = ps2.executeQuery(query_txt);
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
As a side note, consider using PreparedStatement to avoid getting attacked by SQL Injection.
Here's how you use it: -
PreparedStatement ps2 = con.prepareStatement("SELECT * FROM authors WHERE id = ?");
ps2.setInt(1, id);
ResultSet my_rs = ps2.executeQuery();
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
You need to use ResultSet.next() to navigate into the returned data:
if (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
Call my_rs.next(), which will move the ResultSet cursor onto the first row (which you are extracting data out of).
If this is a real application, use PreparedStatements instead of generic Statements. This is an extremely important matter of security if you plan on using user input in SQL queries.

want access resultset of first query for second query

This is java program for SQL statement. I have two queries. Result of the first query is required for second query.
How do I call it in second query?
These results are values for xml tags.
I need to get first query result for this tag
child1.setAttributeNS(xlink,"xlink:type","");
but this is located in 2nd query and if i try to merge those 2 query I get eror resultset closed.
while(rs1.next()){
int i=0,j=0 ,locid,supid;
int lc[]=new int[100];
int sp[]=new int[100];
lc[i] = rs1.getInt(2);
sp[j] = rs1.getInt(1);
lcid=lc[i++];*/
for(i=0;i<loc[i];i++){
for(j=0;j<sup[j];j++){
lcid=lc[i]; spid=sp[j];
System.out.print(spid +" ");
System.out.println(lcid);
String s = (lc[i]==1 ? "simple" : (lc[i]>1 ? "extended" : null));
System.out.println(s); }}}
String querystring=
" ";
rs = stmt.executeQuery(querystring );
while(rs.next()){
Element child1 = doc.createElement("slink");
/
Element element = doc.createElement("loc");
You need to create a brand new and separate Statement for the second ResultSet. Everytime you get a new ResultSet out of a single Statement, every previously opened one will namely be closed.
Replace
rs = stmt.executeQuery(querystring );
by
Statement stmt2 = connection.createStatement();
rs = stmt2.executeQuery(querystring);
Don't forget to add stmt2.close() to the finally block.
Unrelated to the concrete problem, have you considered just JOINing the both queries and using Javabeans to represent the model? This way you end up with a single query and more self-documenting code.

Categories