I need to get a single value from SQLite database. I have 2 tables connected in a multiple way and between them is a middle table. I need to get a value from the middle table, but I am always getting an error and don't understand what I am doing wrong.
This is the hashcode and error:
ResultSet#12c6d7d2
Exception in thread "AWT-EventQueue-0"
java.lang.NumberFormatException: For input string:
"org.sqlite.jdbc4.JDBC4ResultSet#12c6d7d2"
Here is the method:
public int stockProducts(String warehouse, String product){
String sqlSelectStock = "select piw.Stock from ProductsInWarehouse as piw " +
"where piw.idWarehouse in (select w.id from Warehouseas w " +
"where w.nameWarehouse = '" + warehouse + "') " +
"and piw.idProducts in (select p.id from Products as p " +
"where p.nameProduct = '" + product + "');";
ResultSet result = null;
int count = 0;
try {
stmt = povezava.createStatement();
result = stmt.executeQuery(sqlSelectStock);
count = Integer.parseInt(result.toString());
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
result is a ResultSet object and not a String.
This ResultSet object contains the rows returned by the query that you execute.
You must loop (if you are expecting more than 1 rows) through the rows of result and extract the value of the column Stock so you can parse it to an Integer.
I assume (by your code) that you are expecting only 1 row, so change to this
stmt = povezava.createStatement();
result = stmt.executeQuery(sqlSelectStock);
String stock = "0";
if (rs.next()) {
stock = result.getString("Stock");
}
count = Integer.parseInt(stock);
Related
This question already has answers here:
Retrieve column names from java.sql.ResultSet
(14 answers)
Closed 3 years ago.
I have a 3 tables I have joined this query executes and prints out the tables data.
try {
Connection conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
System.out.println("Connected");
Statement st = conn.createStatement();
String query = "SELECT s.*, sup.name as supplierName , p.name as partName "+
"FROM supplies s "+
"INNER JOIN supplier sup on s.supplierNum = sup.supplierNum "+
"INNER JOIN parts p on s.partNum = p.partNum";
ResultSet rs = st.executeQuery(query);
while(rs.next()) {
System.out.println(rs.getString("supplierNum"));
System.out.println(rs.getString("partNum"));
System.out.println(rs.getString("quantity"));
System.out.println(rs.getString("supplierName"));
System.out.println(rs.getString("partName"));
space();
}
} catch(Exception ex) {
System.out.println(ex);
}
But I was trying to add the column names so instead of the console printing:
It would to print the column names cascaded
supplierNum: S1
partNum: P1
quantity: 300
name: Smith
part: Nut
As suggested in https://stackoverflow.com/a/696794/11226302
You need to get the ResultSet meta data to programmatically get your column names from db.
Else, you can manually enter the names as suggested in other answers.
while(rs.next()) {
System.out.println("Supplier Name " + rs.getString("supplierNum"));
System.out.println("Part Name "+rs.getString("partNum"));
System.out.println("Quantity "+ rs.getString("quantity"));
System.out.println("SupplierName "+rs.getString("supplierName"));
System.out.println("PartName "+rs.getString("partName"));
space();
}
You can of course hard-code the column names because you already know them.
If you want to get them programmatically, then use the ResultSetMetaData similar to this:
Connection connection = ...
try (PreparedStatement ps = connection.prepareStatement(QUERY)) {
ResultSet resultSet = ps.executeQuery();
// get the meta data from the result set
ResultSetMetaData rsMeta = resultSet.getMetaData();
// receive the column count
int columnCount = rsMeta.getColumnCount();
// iterate them (their indexes start at 1, I think)
for (int i = 1; i < columnCount + 1; i++) {
// and print the column name, the type and the type name
System.out.println(rsMeta.getColumnName(i)
+ " ("
+ rsMeta.getColumnType(i)
+ ", "
+ rsMeta.getColumnTypeName(i)
+ ")");
}
} catch ...
...
}
If you want to directly output the column in your while loop, then get the meta data before that loop
ResultSetMetaData rsMeta = rs.getMetaData();
and then, inside the loop do
System.out.println(rsMeta.getColumnName(1) + ": " + rs.getString("supplierNum"));
System.out.println(rsMeta.getColumnName(2) + ": " + rs.getString("partNum"));
System.out.println(rsMeta.getColumnName(3) + ": " + rs.getString("quantity"));
System.out.println(rsMeta.getColumnName(4) + ": " + rs.getString("supplierName"));
System.out.println(rsMeta.getColumnName(5) + ": " + rs.getString("partName"));
From a resultSet you can optain his metadata
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
for (int i = 1; i <= cols; i++) {
String colName = meta.getColumnName(i);
System.out.printf("%s=%s\n", colName, rs.getString(i);
...
}
I want to move to the other frame if the query result is empty. How can I check if the query is empty?
String query2 ="Select* from biletbilgileri where FilminÄ°smi='" + filmKoltuk + "'" +
" " + "and" + " " + "SeansTarihi='" + SeansTarihKoltuk + "'" + " " + "and" + " " +
"SeansSaati='" + SeansSaatKoltuk + "'";
Statement stmt1=conn.createStatement();
ResultSet rs1=stmt1.executeQuery(query2);
rs1.next();
if(rs1==null)
{
tesekkurEkrani1.setVisible(true);
tesekkurEkrani1.setSize(1000,500); }
else {
JOptionPane.showMessageDialog(null, "This chair isn't empty!");
}
You want to use SQL count(*) in the query select count(*) from biletbilgileri .... If the returned value is 0, there are no rows returned by your original query.
String query2 = "select count(*) from biletbilgileri ...";
ResultSet rs1 = stmt1.executeQuery(query2);
rs1.next();
int count = rs1.getInt(1);
if (count == 0) {
// empty
}
When you call rs1.next();, it returns a boolean. If the boolean is false, it means there are no more rows. so I think you want to do this:
boolean notEmpty = rs1.next();
if(notEmpty )
{
if (Baglan() == false) { return false; }
try{
String generatedColumns[] = {"ID","TAHSILATNO"};
String sSql = "Declare nId number := 0;" +
" nKey number := 0;" +
" BEGIN" +
" Select Nvl(Max(Id),0) + 1 INTO nId From bvktahsilatno;" +
" INSERT INTO bvktahsilatno (id, yili, tahsilatno ) VALUES( nId, 2018, 53);" +
" EXCEPTION " +
" WHEN DUP_VAL_ON_INDEX THEN" +
" Select Nvl(Max(Id),0) + 1 INTO nId From bvktahsilatno;" +
" Select Nvl(Max(tahsilatno),0) + 1 INTO nKey From bvktahsilatno WHERE Yili = 2018;" +
" INSERT INTO bvktahsilatno (id, yili, tahsilatno ) VALUES( nId, 2018, nKey);" +
"END;";
//VtStatement = VtConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//VtStatement.execute(pSql);
//PreparedStatement VtStatement = VtConnection.prepareStatement( sSql, Statement.RETURN_GENERATED_KEYS );
//PreparedStatement VtStatement = VtConnection.prepareStatement( sSql, generatedColumns );
PreparedStatement VtStatement = VtConnection.prepareStatement( sSql, Statement.RETURN_GENERATED_KEYS);
System.out.println("oracle cumle : " + sSql);
int nAdet = VtStatement.executeUpdate();
System.out.println("Hatayok/Adet : " + nAdet);
ResultSet rs = VtStatement.getGeneratedKeys();
int id=0;
while (rs.next()) {
id = rs.getInt(1);
}
System.out.println("Oracle Inserted ID -" + id); // display inserted record
return true;
} catch (SQLException e) {
return false;
}
I want to ask a question about retrieving created keys on Oracle Db after insert query. My code is as above but generated keys values are not showed on the terminal. How can i get generated column values without creating sequence ? Many form pages say that it is possible as using sequence for id or other column. Also id is primary key, tahsilatno is unique index. I can overcome this problem?
Thank you for your helping from now
I want to get the rs.getInt(1) value and insert that into the param table.
public void () {
result rs;
int id = 0;
final String queryStr = "select MAX(id) from IDEAA";
try {
connect.connect();
rs = connection.executeQuery(queryStr);
while (rs.next()) {
id = rs.getInt(1); // I need to get the value , Here i get the correct value
}
final String querySt = "insert into param(id,param_id,value) values "
+ "(" + id + "," + TEST + ",'" + "TEST" + "'" + ")" // But when it comes here it the becomes zero.
}
Could someone suggest me?
If you could give some more insight in the code (what type is the rs variable and where to get more info on the type (if third party lib))
It still beats me why you would have a while loop since the max id always returns one value the highest.
if might also be worth it to see if you can set the rs to the beginning. (rs.first())
Then try to retrieve the value.
public void () {
result rs;
int id = 0;
final String queryStr = "select MAX(id) from IDEAA";
try {
connect.connect();
rs = connection.executeQuery(queryStr);
rs.first();
id = rs.getInt(1);
final String querySt = "insert into param(id,param_id,value) values "
+ "(" + id + "," + TEST + ",'" + "TEST" + "'" + ")" // But when it comes here it the becomes zero.
}
http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getInt(int)
getInt
int getInt(int columnIndex)
throws SQLException
Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language.
Parameters:
columnIndex - the first column is 1, the second is 2, ...
Returns:
the column value; if the value is SQL NULL, the value returned is 0
Throws:
SQLException - if the columnIndex is not valid; if a database access error occurs or this method is called on a closed result set
This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 9 years ago.
I'm trying to create a query within a results set loop but I keep getting the error "Before start of result set". I've attempted many different methods but they keep coming up with the same error.
Can someone help me out here?
String insertSQL = "INSERT INTO MonthlyReportTable VALUES(NULL,"; //Primary Key.
String PlannetSchemeCode = "";
int ResponcibleAuthorityID = 0;
Statement stmt = ConnectionDetails.getNewConnectionPPARSDB().createStatement();
ResultSet resultsSet = stmt.executeQuery("SELECT * FROM planning_scheme");
Statement insideStatement = ConnectionDetails.getNewConnectionPPARSDB().createStatement();
//Loop though each planning scheme and create the data for each field.
while (resultsSet.next())
{
PlannetSchemeCode = "'" + resultsSet.getString("ps_code") + "'";
//Planning Scheme Primary Key
insertSQL += PlannetSchemeCode + ",";
/*
//Responsible Authority ID
insertSQL += "'" + String.valueOf(
ResponcibleAuthorityID = MySQLUtil.getResults(
ConnectionDetails.Database_Connection_PPARSDB,
"SELECT resp_authority_id " +
"FROM resp_authority_to_ps " +
"WHERE ps_code = " + PlannetSchemeCode
)
.getInt("resp_authority_id")
) + "'";
*/
ResultSet insideResultsSet =
insideStatement.executeQuery(
"SELECT resp_authority_id " +
"FROM resp_authority_to_ps " +
"WHERE ps_code = " + PlannetSchemeCode
);
//ERROR HERE, some reason results set is getting set wrong??
//Error here, this current results set is resetting the Results set.
ResponcibleAuthorityID = insideResultsSet.getInt("resp_authority_id");
//Total_Received_CM
//Add the rest of the values temporary.
int FeildsAdded = 3;
for(int i = 1 + FeildsAdded; i < 458; i++)
{
insertSQL += String.valueOf(0) + ",";
}
//Insert date and end SQL string.
insertSQL += "NOW()";
insertSQL += ")";
System.out.println(insertSQL);
//Do Insert in PPARS.
//stmt.executeQuery(insertSQL);
//Reset the SQL String for the new Row.
insertSQL = "INSERT INTO MonthlyReportTable VALUES(NULL,";
}
A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
You need to call ResultSet#next() before you can read the returned data.
ResultSet insideResultsSet = insideStatement.executeQuery(
"SELECT resp_authority_id " +
"FROM resp_authority_to_ps " +
"WHERE ps_code = " + PlannetSchemeCode
);
if (insideResultsSet.next()) {
ResponcibleAuthorityID = insideResultsSet.getInt("resp_authority_id");
// etc...
}