Display nth row from table DB in Java using getString? - java

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);

Related

Retrieving from database to display as line graph

I am trying to display my data from my database. I am currently doing one query execution at a time to get one particular result for each year. I need to do this for all the columns in my database however this will make the code incredibly messy. Is there an easier way to read the data in from the database to display to a line graph?
Current code snippet:
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
String sql = "SELECT SUM(all_motor_vehicles), Year FROM Vehicle WHERE Year = 2005";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
amount = Integer.parseInt(rs.getString(1)); //get the result
yearFromDB = rs.getString(2);
System.out.println(amount + " " + yearFromDB); //print result
int amount2006;
String yearFromDB2006;
String sql2 = "SELECT SUM(all_motor_vehicles), Year FROM Vehicle WHERE Year = 2006";
pst = con.prepareStatement(sql2);
rs = pst.executeQuery();
amount2006 = Integer.parseInt(rs.getString(1)); //get the result
yearFromDB2006 = rs.getString(2);
System.out.println(amount2006 + " " + yearFromDB2006); //print result
int amount2007;
String yearFromDB2007;
String sql3 = "SELECT SUM(all_motor_vehicles), Year FROM Vehicle WHERE Year = 2007";
pst = con.prepareStatement(sql3);
rs = pst.executeQuery();
amount2007 = Integer.parseInt(rs.getString(1)); //get the result
yearFromDB2007 = rs.getString(2);
System.out.println(amount2007 + " " + yearFromDB2007); //print result
dataset.addValue(amount, allMotorVehicles, yearFromDB);
dataset.addValue(amount2006, allMotorVehicles, yearFromDB2006);
dataset.addValue(amount2007, allMotorVehicles, yearFromDB2007);
JFreeChart chart = ChartFactory.createLineChart("Traffic by Vehicle type", "Vehicle", `"Amount",dataset);`
Snippet of information in database:
Implementing suggested Query giving SQL Error:
Executing query in DB returns:
I can retrieve the year 2005 using rs.getString(1) and it's corresponding number using rs.getString(2) but when I try to retrieve year 2006 and it's number through rs.getString(3) and rs.getString(4) I get an SQLException Error
String sql = "SELECT Year, SUM(all_motor_vehicles) AS allmotor\n" +
"FROM Vehicle\n"
+ "WHERE Year IN (2005, 2006, 2007)\n"
+ "GROUP BY YEAR;";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
amount = Integer.parseInt(rs.getString(2)); //retrieves amount
yearFromDB = rs.getString(1);
System.out.println(amount + " " + yearFromDB); //retrieves year (2005)
System.out.println(rs.getString(3) + " " + rs.getString(4)); //gives me an SQL ERROR
You should instead do a single GROUP BY query in which you aggregate sales by year:
SELECT Year, SUM(all_motor_vehicles) AS all_sales
FROM Vehicle
WHERE Year IN (2005, 2006, 2007) -- or whatever years you want in your report
GROUP BY Year;
I won't bother giving you boilerplate JDBC code for the above query, as you seem to already have the basics of that mastered. Note that I give an alias to the SUM(), in case you would want to access the result set in Java using it.

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.

How to select the last row of database in jsp?

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.

JDBC MySQL DML Statement Insert with Nested Select Performance

FYI - I'm not a developer, but write code when I have to :) Trying to write some java code to update a database in a batched fashion for multiple records. As I'm inserting new rows, I'm querying another table to find relevant data to add relevant date.
The code seems to work, but my problem is performance. I'm seeing that the full batch of dml statements take about 1 second per statement to execute. I'm updating several thousand records, so this job will take quite awhile to execute. So, what I'm looking for is any other ideas on how I can do this while maximizing performance.
Here's what I'm doing right now.
for(Referrer_UpdateSet i : referrerUpdateSet)
{
String dmlStatement = "INSERT INTO TempRefURL (firstTouchDate) " +
"(SELECT activityDateTime as firstTouch "+
"FROM referrer_URL_backup_10292014 "+
"WHERE mktPersonId = ? "+
"ORDER BY activityDateTime ASC LIMIT 1)";
stmt = mktoUTMConn.prepareStatement(dmlStatement);
stmt.setInt(1, i.id);
//System.out.println(stmt+" \n");
stmt.executeUpdate();
}
mktoUTMConn.commit();
I'm also trying preparedStatements.addBatch, but it doesn't seem to be working (only 1 row inserted..)
System.out.println("updating temp table with referrer URL data");
//iterate through array of parsed referrer URLs
String dmlStatement = "UPDATE dml_sandbox.TempRefURL SET Referrer_URL = ? " + "WHERE id = ?";
for(Referrer_UpdateSet i : referrerUpdateSet){
stmt = mktoUTMConn.prepareStatement(dmlStatement);
stmt.setInt(2, i.id);
stmt.setString(1, i.cleanURL);
//System.out.println(stmt+" \n");
stmt.addBatch();
//stmt.executeUpdate();
//System.out.println(stmt+" \n");
}
stmt.executeBatch();
System.out.println("Done updating temp table with referrer URL data");
mktoUTMConn.commit();
Any suggestions would be greatly appreciated. Thanks!
Simple fix. See my comment above. Here's the new code:
String dmlStatement = "UPDATE dml_sandbox.TempRefURL SET Referrer_URL = ? " + "WHERE id = ?";
stmt = mktoUTMConn.prepareStatement(dmlStatement);
//iterate through array of parsed referrer URLs
for(Referrer_UpdateSet i : referrerUpdateSet){
stmt.setInt(2, i.id);
stmt.setString(1, i.cleanURL);
stmt.addBatch();
stmt.executeUpdate();
}
System.out.println(stmt+" \n");
int[] recordsAffected = stmt.executeBatch();
System.out.println("Done updating temp table with referrer URL data");
System.out.println(recordsAffected.length + " records affected");
mktoUTMConn.commit();

Getting row count with Result Set

Please Help !!!!!!!
In DB I have 2 rows with this query.
SELECT D.DEALER_CODE
FROM SCOTT.T_DEALERSHIP D,SCOTT.T_DEALER_BILLING DB
WHERE D.DEALER_CODE = DB.DEALER_CODE
AND DEALER_NAME LIKE 'XTIME%'
AND (RNR_CUST_NUM = '546' OR RNR_CUST_NUM = '43356'OR RNR_CUST_NUM = '7637055' OR RNR_CUST_NUM ='7637055' OR RNR_CUST_NUM IS NULL)
AND (RCI_STORE_NUMBER IS NULL OR RCI_STORE_NUMBER = '05')
AND (RCI_AREA_NUMBER = '01'OR RCI_AREA_NUMBER IS NULL)
AND (RCI_DEALER_NUMBER IS NULL AND DEALER_Address1 LIKE UPPER('1500 ORACLE%')
AND DEALER_CITY =UPPER('BAKERSFIELD') AND DEALER_ZIP LIKE'6%')
With below code, I get only 1 row when there are 2 records in DB. When there is only one record in DB it works but not when there are more records. Also rs.last() method gets skipped and exits resultset. I have to comment it to execute for one record. I do not want to use COUNT.
ResultSet rs = stmt.executeQuery(sql1);
System.out.println("" + sql1);
while(rs.next()) {
rs.last();
int Rows = rs.getRow();
System.out.println("Rows are " + Rows);
}
If all you want to do is count the records in the database, then you should really use a query of the form SELECT count(*) FROM .... If you really need to perform the query the way you listed above, then you want to set a counter variable outside your while loop like so:
int rowNum = 0;
while (rs.next()) {
rowNum++;
}
System.out.println("Number of records: "+rowNum);
I strongly recommend against returning all the data to Java via JDBC just to determine the number of rows. If you just want to know how many rows match the condition, then do a select count(*) query:
In SQL:
SELECT COUNT(*)
FROM SCOTT.T_DEALERSHIP D,SCOTT.T_DEALER_BILLING DB
WHERE D.DEALER_CODE = DB.DEALER_CODE
AND DEALER_NAME LIKE 'XTIME%'
AND (RNR_CUST_NUM = '546' OR RNR_CUST_NUM = '43356'OR RNR_CUST_NUM = '7637055' OR RNR_CUST_NUM ='7637055' OR RNR_CUST_NUM IS NULL)
AND (RCI_STORE_NUMBER IS NULL OR RCI_STORE_NUMBER = '05')
AND (RCI_AREA_NUMBER = '01'OR RCI_AREA_NUMBER IS NULL)
AND (RCI_DEALER_NUMBER IS NULL AND DEALER_Address1 LIKE UPPER('1500 ORACLE%')
AND DEALER_CITY =UPPER('BAKERSFIELD') AND DEALER_ZIP LIKE'6%')
Then in Java:
ResultSet rs = stmt.executeQuery(sql1);
System.out.println("" + sql1);
int rows = 0;
if(rs.next()) {
rows = rs.getInt();
}
System.out.println("Rows are " + rows);
Edit based on OP's comments
To get the values from the database in addition to the count, just scan the values.
SQL:
SELECT D.DEALER_CODE
FROM SCOTT.T_DEALERSHIP D,SCOTT.T_DEALER_BILLING DB
WHERE D.DEALER_CODE = DB.DEALER_CODE
AND DEALER_NAME LIKE 'XTIME%'
AND (RNR_CUST_NUM = '546' OR RNR_CUST_NUM = '43356'OR RNR_CUST_NUM = '7637055' OR RNR_CUST_NUM ='7637055' OR RNR_CUST_NUM IS NULL)
AND (RCI_STORE_NUMBER IS NULL OR RCI_STORE_NUMBER = '05')
AND (RCI_AREA_NUMBER = '01'OR RCI_AREA_NUMBER IS NULL)
AND (RCI_DEALER_NUMBER IS NULL AND DEALER_Address1 LIKE UPPER('1500 ORACLE%')
AND DEALER_CITY =UPPER('BAKERSFIELD') AND DEALER_ZIP LIKE'6%')
Java:
ResultSet rs = stmt.executeQuery(sql1);
System.out.println("" + sql1);
List<String> rows = new ArrayList<String>();
while(rs.next()) {
rows.add(rs.getString());
}
System.out.println("There are " + rows.size() + " rows.");

Categories