How to select the first row/line from database - java

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.

Related

passing parameter to outer table of a subquery in a prepered statement in Java

Im implementing a subquery in java which requires 2 parameters to be fed using a prepared statement.
Passing parameter within the inner query is working but then parameter is not passed to the outer one.
During execution i get an error on stacktrace saying :No operations allowed after statement closed. and hence the prepared statement returns wrong results.Question: How best can i pass the parameter successfully to the outer table.
Below is a sample code of my implementation
pst = conn.prepareStatement("SELECT slot.time_slot_id,slot.`date`,slot.count FROM
(SELECT time_slot_id,ue.`date`,COUNT(ue.user_id) AS count FROM user_event ue
RIGHT JOIN `time_slot` t ON ue.time_slot_id = t.id
WHERE ue.status= 1 AND event_id=?
GROUP BY ue.`date`,time_slot_id
) AS slot WHERE slot.count >=? ");
pst.setInt(1,eventId);
//here is the parameter that is passed to the outer table
pst.setInt(2,count);
rs = pst.executeQuery();
here is an update for the entire method am implementing as below;
public static DefaultListModel Fetch(int eventId){
DBconnection.connect();
DefaultListModel fetchedSlots= new DefaultListModel();
try{
//
pst = conn.prepareStatement("SELECT slot.time_slot_id,slot.`date`,slot.count FROM \n" +
"(SELECT time_slot_id,ue.`date`,COUNT(ue.user_id) AS count FROM user_event ue \n" +
"RIGHT JOIN `time_slot` t ON ue.time_slot_id = t.id\n" +
"WHERE ue.status= 1 AND event_id=?\n" +
"GROUP BY ue.`date`,time_slot_id) AS slot\n" +
"WHERE slot.count >? ");
pst.setInt(1,eventId);
//here a function is invocked using eventId to get counts
pst.setInt(2,FetchCounts(eventId));
rs = pst.executeQuery();
while(rs.next()){
fetchedSlots.addElement(new ModelSlot(rs.getInt("time_slot_id"),rs.getString("date")));
}
DBconnection.CloseConnection();
}catch (SQLException ex){
System.out.println(ex.getMessage());
}
return fetchedSlots;
}
I assume that the error happen in case like this :
Open statement
...
Use statement
...
Close statement <---------- You can't use your statement after close it
...
Use same statement again <---------- You are here, your statement is close
To solve your problem you have two choices :
Close the statement in the end of your work, you can check this Closing Database Connections in Java
Open a new statement, for example statement = connection.createprePareStatement();
EDIT
Like i said before, your problem is with connection, when you call this method :
pst.setInt(2, FetchCounts(eventId));
//---------------^^^
In fact this open a new connection, then close it in the end, so when you execute your query it rs = pst.executeQuery();, the connection is closed, and this cause this problem, so don't close the connection in your method FetchCounts(T eventId);.
After trials, i concatenated the second parameter to the prepared statement rather than before and it worked.
AS below;
pst = conn.prepareStatement("SELECT
slot.time_slot_id,slot.`date`,slot.count FROM \n" +
"(SELECT time_slot_id,ue.`date`,COUNT(ue.user_id) AS count FROM user_event ue \n" +
"RIGHT JOIN `time_slot` t ON ue.time_slot_id = t.id\n" +
"WHERE ue.status= 1 AND event_id=?\n" +
"GROUP BY ue.`date`,time_slot_id) AS slot\n" +
"WHERE slot.count >" + FetchCounts(eventId));
pst.setInt(1,eventId);
rs = pst.executeQuery();
AS evident above, the result of the invoked method FetchCounts(eventId) is passed directly to the outer table of the subQuery within the prepared statement.

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

Wrong SQL in Java

I am trying to run a SQL statement in Java and I am getting syntax
String number,key; //populate number and key.
rs = stmt.executeQuery("select count(*)
from users_transition
where phoneNumber =" +number +"and randKey="+key);
In MySQL database, phoneNumber is BigInt(20) and key is Int(11).
Also, according to this link. The table 5.1 says that types in MYSQl can be converted to what types in Java. Doesnt the other way round would work too?
Here's the ERROR
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'randKey=9999' at line 1
You are missing a space between the number and the AND operator:
rs = stmt.executeQuery("select count(*) from users_transition where phoneNumber =" +number +" and randKey="+key);
// ^
You should replace the query with prepared statement, and use query parameters. This would help you not only avoid simple errors like this, but also make your code immune to SQL injection attacks.
String sql = "select count(*) from users_transition where phoneNumber =? and randKey=?";
PreparedStatement getCount = con.prepareStatement(sql);
getCount.setBigDecimal(1, new BigDecimal(number));
getCount.setBigDecimal(2, new BigDecimal(randKey));
I'll tell you what is wrong, and then I'll tell you what is very wrong.
What is wrong
First, you are building a query which where has missing spaces (and possibly missing quotes):
String number,key; //populate number and key.
rs = stmt.executeQuery("select count(*) "
+ "from users_transition "
+ "where phoneNumber =" +number +" and randKey="+key)";
// ^ you missed a space here
What is very wrong
Your query is vulnerable to SQL Injection Attacks (please read the link, it provides a humorous example and tips on solving the problem). Use prepared statements to do this kind of thing:
String number, key;
PreparedStatement ps = conn.prepareStatement("select count(*) "
+ "from users_transition "
+ "where phoneNumber=? "
+ " and randKey=?");
// The question marks are place holders for values
// You can assign this values with setXXX() methods
ps.setString(1, number);
ps.setString(2, randKey);
ResultSet rs = ps.executeQuery();
// Do whatever you need to do with the ResultSet

How to use MySQL subquery in JDBC?

Example query:
SELECT country
FROM data
WHERE city LIKE
(SELECT LEFT ('jakartada',7));
Example in JDBC:
String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT ('?',7)) ";
PreparedStatement ps = koneksi.prepareStatement(sql);
ps.setString(1, city );
ResultSet rs = ps.executeQuery();
Why this doesn't work properly?
There is no parameter within the prepared statement, however the code attempts to set a parameter. Try adding a parameter to the statement.
String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT (?,7)) ";
PreparedStatement ps = koneksi.prepareStatement(sql);
ps.setString(1, city );
ResultSet rs = ps.executeQuery();
Or try removing the statement setting the parameter:
String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT ('jakartada',7)) ";
PreparedStatement ps = koneksi.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
I believe you're making this harder than it needs to be, and at the same time you're missing something. Is this what you're trying to do?
SELECT country FROM data WHERE city LIKE 'jakarta%'
That is, are you looking for the country column from every row where the city name starts with 'jakarta'? If so, don't forget the % sign. If you don't include the % sign, then
SELECT country FROM data WHERE city LIKE 'jakarta'
and
SELECT country FROM data WHERE city = 'jakarta'
mean exactly the same thing as each other, and the LIKE operator is pointless; you may as well use the = operator.
So, it seems to me the MySQL query you want is
SELECT country FROM data WHERE city LIKE CONCAT(LEFT('jakartada',7),'%')
to add the % sign. You don't need the subselect in this case.
Like you pointed out, the Java code you need then is:
String sql = "SELECT country FROM data " .
"WHERE city LIKE CONCAT(LEFT(?,7),'%')";
PreparedStatement ps = koneksi.prepareStatement(sql);
ps.setString(1, city );
ResultSet rs = ps.executeQuery();
... process the rs records ...
rs.close(); /* please don't forget to close your result sets */
use this link for your solution and this query
http://sqlfiddle.com/#!2/c79ab/10
SELECT country FROM data
WHERE city LIKE CONCAT(LEFT('jakartada',7),'%')
Don't you quotes in your prepared statement when setting values at runtime... Otherwise it will take it as input only not for ps position... Remove single quotes from your question mark...

SQL Where Clause with Values Provided

I am trying to use a SQL Select statement for a query in Java. I currently have the following:
ResultSet rs = stmt.executeQuery("SELECT *" +
" FROM " + table +
" WHERE " + selection +
" VALUES " + selectionArgs);
where "selection" is a string and "selectionArgs" is a string array.
String selection = "documentFK=?";
String[] selectionArgs = { ... };
Is it possible to use the VALUES command to replace the ? like in with the INSERT command? Either way, what would be the correct syntax?
Thanks for the help.
I believe what you're looking for is the IN statement. Your query should look like this:
SELECT *
FROM table
WHERE documentFK IN ('doc1', 'doc2', 'doc3')
AND userFK IN ('user1', 'user2', 'user3')
This is (obviously) going to make your code a bit more ugly. You'll have to ensure that the WHERE keyword is used for the first clause, but the AND keyword is used for every other clause. Also, each list will have to be comma-delimited.
no, that is not the way it's done. first you create the statement from the query, using the question marks as place holders for the real values you want to put there. then you bind these values to the statement.
//the query
String sql = "SELECT " + "*" +
" FROM " + table +
" WHERE documetFK = ?";
//create the statement
PreparedStatement stmt = connection.prepareStatement(sql);
//bind the value
stmt.setInt(1, 4); //1 is "the first question mark", 4 is some fk
//execute the query and get the result set back
ResultSet rs = stmt.executeQuery();
now, if you want this thing with selection string and some args, then you're going to have a loop in your java code. not sure what your array looks like (you're not giving me that much to go on), but if it's made up from strings, it would be something like this:
//the query
String sql = "SELECT " + "*" +
" FROM " + table +
" WHERE " + selection;
//create the statement
PreparedStatement stmt = connection.prepareStatement(sql);
//bind the values
for(int i = 0; i < selectionArgs.length; i++) {
stmt.setString(i, selectionArgs[i]); //i is "the nth question mark"
}
//execute the query and get the result set back
ResultSet rs = stmt.executeQuery();
Can you use a PreparedStatement?
First of all SELECT .. WHERE .. VALUES is incorrect SQL syntax. Lose the VALUES part.
Then you're looking for prepared statements.
In your example it's going to look something like this:
String sql = "SELECT * FROM myTable WHERE documentFK=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "myDocumentFK"); // parameters start from 1, not 0. also we're assuming the parameter type is String;
ResultSet rs = pstmt.executeQuery();
Or with multiple parameters:
String sql = "SELECT * FROM myTable WHERE documentFK=? AND indexTerm=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "myDocumentFK"); // parameters start from 1, not 0. also we're assuming the parameter type is String;
pstsm.setInt(2, 100); // assume indexTerm can be 100 and is an integer
ResultSet rs = pstmt.executeQuery();
However, all of this doesn't worth your while since you can simply do the same by concatenating the value into the statement. But be aware of the SQL injections, so don't forget to escape the parameters that you're passing into the database.
PS: I was typing this way too long. You already have the answers :-)
As a side note, you may want to take a look at this to prevent SQL injections:
https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java
Sormula can select using "IN" operator from a java.util.Collection of arbitrary size. You write no SQL. It builds the SQL SELECT query with correct number of "?" parameters. See example 4.

Categories