How to select the last row of database in jsp? - java

I am not able to display the last row of my database in jsp. I already tried to print rs.getString(1), but it does not work.
ResultSet rs = st.executeQuery("Select MAX(CustomerID) from Customer");
while(rs.next()){out.print(rs.getString(1));}

I don't know if this is what you want but if you are trying to get the whole row there are some ways to accomplish that
ResultSet rs = st.executeQuery("select max(customerid) as id from customer");
rs.next();
String id = rs.getString("id");
rs = st.executeQuery("select field_a, field_b from customer where customerid = " + id);
rs.next();
String row = id + "," + rs.getString("field_a") + "," + rs.getString("field_b");
out.println(row);
Of course you need to replace the field_a and field_b columns with the ones in your customer table and add or remove columns according to your needs.
The shorter way is using order by and limit keywords like this
ResultSet rs = st.executeQuery("select customerid, field_a, field_b from customer order by customerid desc limit 1");
rs.next();
String row = rs.getString("customerid") + "," + rs.getString("field_a") + "," + rs.getString("field_b");
out.println(row);
Be secure of add a primary key or unique constraint to the customerid column for improve the performance of the both methods.

Related

How to select the first row/line from database

I am trying to make a java program program can takes just one row/line from phpMyAdmin database. what I mean is in the photo
The problem is that I couldnt figure out how to take just the first line because its always keep giving me all the id'S , dafat's , etc. Is there any way I can get every line alone or even every data alone (jsut 1 id from the first line for example). I would appreciate who can help me with this.
Connection con = myConnection.getconnection();
try{
PreparedStatement ps = con.prepareStatement("SELECT `id`, `dafat`, `sinif`, `adet`, `price`, `type`, `total` FROM "+ff1+" WHERE 1 ");
ResultSet resultset = ps.executeQuery();
System.out.println(resultset.getString("id"));
}
catch (Exception e) {
}
Use the LIMIT clause:
PreparedStatement ps = con.prepareStatement(
"SELECT `id`, `dafat`, `sinif`, `adet`, `price`, `type`, `total` FROM "
+ ff1 + " LIMIT 1");
If you want the first id value (the smallest one) you can combine with ORDER BY, as in:
PreparedStatement ps = con.prepareStatement(
"SELECT `id`, `dafat`, `sinif`, `adet`, `price`, `type`, `total` FROM "
+ ff1 + " ORDER BY id LIMIT 1");
Replace WHERE whit LIMIT
PreparedStatement ps = con.prepareStatement("SELECT `id`, `dafat`, `sinif`, `adet`, `price`, `type`, `total` FROM "+ff1+" ORDER BY id LIMIT 1 ");
Use Rownum in your where clause like:
"SELECT * FROM all_objects WHERE rownum < 2"
https://mfaisal1521.blogspot.com/2020/04/rownum-in-sql.html
And also resultset.getString("id") start fetch result from first index of query untill we dont move our cursor to next resultset.

Display nth row from table DB in Java using getString?

I want to show data from a Table Database using SQLite in JAVA
my code:
String sql = "SELECT * FROM DIC";
rs = st.executeQuery(sql);
System.out.println("row 1: " + rs.getString("WORD")); // WORD is a column label
System.out.println("row 3: " + rs.getString("WORD"))
With DIC is my table
so How do I can show value in nth row ( ex: 2nd, 3th,.. row)???
Specifically, I want my code print out as desired. Thank you!
String sql = "SELECT * FROM DIC";
rs = st.executeQuery(sql);
int rowCount = 0;
while(rs.next){
rowCount++
if(rowCount == ?) {
System.out.println("row 1: " + rs.getString("WORD"));
System.out.println("row 3: " + rs.getString("WORD"))
}
}
You could use OFFSET in you query and use prepared statement
SELECT mycol FROM DIC ORDER BY mycol LIMIT 1 OFFSET ?;
And you need to bind it as
stmt.setInt(1,nth_row);

How to get the return with executeQuery() in Java?

I have this code;
String sql = "UPDATE Players SET Losses=Losses+1 WHERE UUID='" + p.getUniqueId() + "';";
stmt.executeUpdate(sql);
How can I get the current Losses for a specific Player p?
SELECT query will return it, but what's your real question?
String sql ="SELECT column_name,column_name FROM table_name WHERE column_name ="" ;";
I would use a Select for Update, and something like this -
String query = "SELECT Losses FROM Players FOR UPDATE "
+ "Players SET Losses=Losses+1 WHERE UUID=?";
ps = conn.prepareStatement(query,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
ps.setString(1, p.getUniqueId());
ResultSet rs = ps.executeQuery();
int losses = 0;
if (rs.next()) {
losses = rs.getInt("Losses");
}
You can get the losses like the following. Seems really trivial, guess you are an absolute beginner.
String sql = "SELECT Losses FROM Players WHERE UUID='" + p.getUniqueId() + "';";
ResultSet rs = stmt.executeQuery(sql);
int losses = -1;
if(rs.next()) {
losses = rs.getInt("Losses");
}
You'd have to make a SELECT statement. Like SELECT losses FROM Players WHERE UUID='"+p.getUniqueId()+"';";
Then use Statement's executeQuery() which returns a ResultSet. You can use an iterator to extract the data from the ResultSet object.

How to concatenate 3 resultset values together in jtextfield?

I am trying to concatenate 3 resultset values from my database and display them together in one textfield but its not working i am getting only last value that is "city" displayed in textbox.
PreparedStatement stmt2 = con.prepareStatement("select bk_name as bank,bk_branch as branch,bk_add as city from bk_det WHERE rm_id = ?");
ResultSet rs2;
String rm2 = tf_rmid.getText().trim();
stmt2.setInt(1, Integer.parseInt(rm2));
rs2 = stmt2.executeQuery();
while (rs2.next()) {
tf_remby.setText(rs2.getString("bank"));
tf_remby.setText(rs2.getString("branch"));
tf_remby.setText(rs2.getString("city"));
}
I tried doing:
tf_remby.setText(rs2.getString("bank"+","+"branch"+","+"city"));
and also
tf_remby.setText(rs2.getString("bank"+"branch"+"city"));
but neither works. Does anyone have any suggestions/solutions?
In your while loop, you could try something like:
String text = rs2.getString("bank") + ", " +
rs2.getString("branch") + ", " +
rs2.getString("city");
tf_remby.setText(text);
But if you have multiple values in the result set, you'll only see the last bank/branch/city record anyway.

How to get a particular column's values alone?

I am using the mysql java connector. I need java to display the contents of the first column and the second column in different steps. How do I achieve this?
String qry = "select col1,col2 from table1";
Resultset rs = statement.executeQuery(qry);
I've posted a sample below:
Statement s = conn.createStatement ();
s.executeQuery ("SELECT id, name, category FROM animal");
ResultSet rs = s.getResultSet ();
int count = 0;
while (rs.next ())
{
int idVal = rs.getInt ("id");
String nameVal = rs.getString ("name");
String catVal = rs.getString ("category");
System.out.println (
"id = " + idVal
+ ", name = " + nameVal
+ ", category = " + catVal);
++count;
}
rs.close ();
s.close ();
System.out.println (count + " rows were retrieved");
(From: http://www.kitebird.com/articles/jdbc.html#TOC_5 )
Edit: just re-read the question and think you might mean you want to refer to a column later on in code, instead of in the inital loop as in my example above. In that case, you can create an array and refer to the array later on, or, as another answer suggests you can just do another query.
Load them into any data structure of your choice and then display them to your heart's content.
List<String> firstCol = new ArrayList<String>();
List<String> secondCol = new ArrayList<String>();
while(rs.next()){
firstCol.add(rs.getString("col1"));
secondCol.add(rs.getString("col2"));
}
Then you can manipulate with the two list as you want.
How about ... (insert drumroll here):
String qry1 = "select col1 from table1";
Resultset rs1 = statement.executeQuery(qry);
String qry2 = "select col2 from table1";
Resultset rs2 = statement.executeQuery(qry);
(You might want to phrase your question more clearly.)
You can do it like this :
String sql = "select col1,col2 from table1";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) System.out.println(rs.getString("col1"));
I am using following Code:
Statement sta;
ResultSet rs;
try {
sta = con.createStatement();
rs = sta.executeQuery("SELECT * FROM TABLENAME");
while(rs.next())
{
Id = rs.getString("COLUMN_Name1");
Vid = rs.getString("COLUMN_Name2");
System.out.println("\n ID : " + Id);
System.out.println("\n VehicleID: " + Vid);
}
}
catch(Execption e)
{
}
And this code is 100% working.
String emailid=request.getParameter("email");
System.out.println(emailid);
rt=st.executeQuery("SELECT imgname FROM selection WHERE email='emailid'");
System.out.println(rt.getString("imgname"));
while(rt.next())
{
System.out.println(rt.getString("imgname"));
finalimage=rt.getString("imgname");
}

Categories