This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 9 years ago.
I am getting the error Before start of result set I thought that I had to use next() on the ResultSet before retrieving data from the ResultSet ?
public void getPersonsOrders(String firstName){
Connection con = connect();
try{
Statement s = con.createStatement();
s.executeUpdate("use stl;");
ResultSet rs1 = s.executeQuery("select personID from person where first_name = " +"'"+firstName+"'"+";"); //get persons ID no.
ResultSet rs2 = s.executeQuery("select * from orderr where personID = "+rs1.getInt(1)+";"); //use ID no. to
rs2.next();
for(int i = 1; i < 4; i++){ //retrive order
System.out.println(rs2.getInt(i));
}
}
catch(SQLException e){
System.out.println("3" +e.getMessage());
}
}
You should execute
rs1.next();
before
ResultSet rs2 = s.executeQuery("select * from orderr where personID = "+rs1.getInt(1)+";");
Remember that you should close opened resources.
Regards.
You can use the following mechanism.
resultSet=s.executeQuery("select personID from person where first_name = " +"'"+firstName+"'"+";");
if (resultSet!= null)
{
do
{
//You can code your business logic here by getting data from db like:
System.out.println(resultSet.getString("first_name"));
} while (resultSet.next());
You don't call rs1.next() before reading from it with rs1.getInt(1).
As an aside, you can do this with a single SQL statement with a join are follows:
SELECT orderr.* FROM orderr JOIN person ON orderr.personID = person.personID WHERE person.first_name = ?
You should also use a java.sql.PreparedStatement like this:
PreparedStatement preparedStatement = connection.prepareStatement("SELECT orderr.* FROM orderr JOIN person ON orderr.personID = person.personID WHERE person.first_name = ?");
preparedStatement.setString(1, firstName);
ResultSet resultSet = preparedStatement.executeQuery();
The database will cache the query plan, which will help performance plus it will prevent SQL injection attacks.
Related
I have sql query which is shown below its a select statement I want to pass dynamically the values but I am not aware how can we do it .here I want to pass product and location dynamically
can anyone help in this ..
public static ResultSet RetrieveData() throws Exception {
PreparedStatement statement;
String sql = "select * FROM Courses WHERE "
+ "product = product? "
+ "and location = location? ";
System.out.println(sql);
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
String mysqlUrl = "jdbc:mysql://localhost:3306/wave1_build";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "root");
statement = con.prepareStatement(sql);
ResultSet rs = statement.executeQuery(sql);
return rs;
One approach is to use plain ? placeholders along with the appropriate setters to bind values:
String sql = "SELECT * FROM Courses WHERE product = ? AND location = ?";
statement = con.prepareStatement(sql);
statement.setString(1, "some product");
statement.setString(2, "some location");
// NOTE: executeQuery() when used with prepared statements does NOT take any parameters
ResultSet rs = statement.executeQuery();
I want to execute the following query in java, through mysql jdbc: SELECT COUNT (*) FROM ORDERS, CUSTOMER WHERE O_ORDEYKEY = O_CUSTKEY
I have this code:
Connection conn = new DatabaseConnection().createMySQLConnection();
int totalRows=0;
for(int j=0;j<tables.size();j++)
{
Statement stmt = null;
ResultSet rs = null;
int rowCount = -1;
try {
conn.setAutoCommit(false);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tables.get(j)
+ " WHERE O_ORDERKEY = O_CUSTKEY;");
rs.next();
rowCount = rs.getInt(1);
totalRows= totalRows+rowCount;
} finally {
rs.close();
stmt.close();
}
}
But I wanted to run it faster. How can I do this ?
For easier reading you should avoid the old implicit join syntax based on where and use the SQL standard (since 1992) explicit join syntax:
SELECT COUNT (*)
FROM ORDERS
INNER JOIN CUSTOMER ON ORDERS.O_ORDEYKEY = CUSTOMER.O_CUSTKEY
For better performance be sure you have an index on:
table ORDERS column O_ORDEYKEY
table CUSTOMER column O_CUSTKEY
Im running the code and keep getting the Resultset is closed, is there something wrong with the loops? The Strings that is taken from the for() has multiple "SUBKATEGORIER" aswell. Pls help me I'm new to Java.
Object[] valt = jList1.getSelectedValues();
for (Object ettVal : valt) {
String enSuperkategori = ettVal.toString();
System.out.println(enSuperkategori);
try {
Statement stmt2 = connection.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT SUBKATEGORIID FROM
SUBKATEGORI JOIN SUPERKATEGORI ON SUPERKATEGORI.SUPERKATEGORIID =
SUBKATEGORI.SUPERKATEGORI WHERE SUPERKATEGORI.SKNAMN ='" + enSuperkategori
+"'");
while(rs2.next());
{
PreparedStatement ps2 = connection.prepareStatement("INSERT
INTO ANVANDARE_SUBKATEGORI (ANVANDARE,SUBKATEGORI) VALUES(?,?)");
ps2.setString(1, angivetAnv);
ps2.setInt(2, rs2.getInt("SUBKATEGORIID"));
System.out.println(rs2.getInt("SUBKATEGORIID"));
ps2.executeUpdate();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
I don't know the exact cause of the error, but my guess is that your first result set is getting closed as soon as you run the inner insert. The good news is that you may run your entire insert using the following single query:
INSERT INTO ANVANDARE_SUBKATEGORI (ANVANDARE, SUBKATEGORI)
SELECT SUBKATEGORIID, SUBKATEGORIID
FROM SUBKATEGORI s
INNER JOIN SUPERKATEGORI sp
ON sp.SUPERKATEGORIID = s.SUPERKATEGORI
WHERE sp.SKNAMN = ?
Your relevant Java code:
String sql = "INSERT INTO ANVANDARE_SUBKATEGORI (ANVANDARE, SUBKATEGORI) ";
sql += "SELECT SUBKATEGORIID, SUBKATEGORIID ";
sql += "FROM SUBKATEGORI s ";
sql += "INNER JOIN SUPERKATEGORI sp ";
sql += "ON sp.SUPERKATEGORIID = s.SUPERKATEGORI ";
sql += "WHERE sp.SKNAMN = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, enSuperkategori);
ps.executeUpdate();
Im working with Sql and java.
This works in sql:
use mybank
Select * from Account
inner join CustomerAccount on accountid = id
where customerid = 18
In java i write this:
String sql = ("Select * From Account inner join CustomerAccount on accountid = id where customerid =?;");
try (Connection con = myDbManager.getConnection())
{
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, customer.getId());
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
customer.getId gives me 18.
but i get this error;
Incorrect syntax near '?'.
The problem is here:
ResultSet rs = st.executeQuery(sql);
You're using Statement#executeQuery(String sql) which is inherited from Statement interface. You should use PreparedStatement#executeQuery.
In short, change that line to:
ResultSet rs = ps.executeQuery();
^ parameter-less
And remove this Statement variable from your code, it will just confuse you and future readers of the code:
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, customer.getId());
//Statement st = con.createStatement();
^ this generates confusion
Also, you should remove the semicolon in your SQL statement when executing it form Java:
String sql = "Select *"
+ " From Account"
+ " inner join CustomerAccount"
+ " on accountid = id"
+ " where customerid = ?";
SQL-Queries in Java don't use the ';':
String sql =( "Select * From Account inner join CustomerAccount on accountid = id where customerid =?");
How can i find out, from a Java program using JDBC if my table has a record with a specific primary key value? Can i use the ResultSet somehow after i issue a SELECT statement?
Count might be a better idea for this case. You can use it like so:
public static int countRows(Connection conn, String tableName) throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName + " WHERE.... ");
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
} finally {
rs.close();
stmt.close();
}
return rowCount;
}
Taken from here.
You can do something like
private boolean hasRecord(String id) throws SQLException {
String sql = "Select 1 from MyTable where id = ?";
PreparedStatement ps = dbConn.prepareStatement(sql);
ps.setString(1,id);
ResultSet rs = ps.executeQuery();
return rs.next();
}
You can do that in four steps.
Write SQL. Something like select count(1) from table where column = 34343 will do.
Learn how to get connection using JDBC.
Learn about PreparedStatements in Java.
Learn how to read values from ResultSet.
select case
when exists (select 1
from table
where column_ = '<value>' and rownum=1)
then 'Y'
else 'N'
end as rec_exists
from dual;