I'm having a trouble when retrieving in a very simple SELECT query.
I'm trying to retrieve all information from table 'db_con_type' and put them in array String of dbChoices.
Database:
The Select query works fine in report designer. Sorry i can't upload the images since i'm new here.
Code:
public void setDbTypeChoices()
{
try
{
con2db connect2db = new con2db();
con = connect2db.aksesDatabase();
stmt = con.createStatement();
String sql = "SELECT * FROM db_con_type";
rs = stmt.executeQuery(sql);
int i = 0;
while(rs.next())
{
this.dbChoices[i] = rs.getString("DB_Type");
i++;
}
rs.close();
stmt.close();
ps.close();
con.close();
//Close Connection
connect2db.tutupKoneksi();
}
catch(Exception e)
{
System.out.println("SQL ERROR 1 = " + e.getMessage());
System.out.println("SQL ERROR 2 = " + e.toString());
}
}
Error:
SQL ERROR 1 = null
SQL ERROR 2 = java.lang.NullPointerException
Question:
Any idea what is happening? Any Solution?
Thanks
By the way, it is a good practice that if you are handing ResultSet that you first check if the result set returned is not null before operating on it e.g. rs.next() which will give you a NPE if rs is null.
if(rs != null) {
while(rs.next()) {
this.dbChoices[i] = rs.getString("DB_Type");
i++;
}
}
Found the problem. it's because of the ps.close() code..
since i don't use it here but i close it and it rises a problem..
thanks to the printStackTrace idea by Luiggi.
thanks for all answers. i really appreciate it.. :D
Related
I am working on a program which will when finished allow the end user to keep track of there sound packs in a database through SQLite. The newest problem I am running into is that I can not get the Select statement to take a JTextField input. The reason that I want to do this is that I already have the text fields linked through the insert method. I have tried switching the variable types in the readAllData method and I am not entirely sure what other way to fix it.
The fields are as follows
PackId
PackName
VendorName
PackValue
what I want to happen is when I hit the Update button I want the data in the database to print out to the console (for now) and I am also going to be adding a select specified records method as well.
Here is the code I do apologize in advance this is a very long project:
public void readAllData() throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:sqlite:packsver3.db");
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = "SELECT * FROM packs";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
String PackId = PackId.getText();
String PackName = PackName.getText();
String VendorName = VendorName.getTextField();
String PackValue = rs.getTextField;
System.out.println("All Packs\n");
System.out.println("PackId: " +PackId);
System.out.println("PackName: " +PackName);
System.out.println("VendorName: " +VendorName);
System.out.println("PackValue: " +PackValue+"\n\n");
}
} catch (SQLException e) {
System.out.println(e.toString());
}finally {
try {
assert rs != null;
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
System.out.println(e.toString());
}
Console Output
I can't find the mistake, I get this error:
Error: net.ucanaccess.jdbc.UcanaccessSQLException: unexpected token: = required: AS
This is my code. Can you help me find it? Thanks in advance.
package database;
// Imports
import java.sql.*;
public class DBConnect {
// Path to Database
final static String DB = "jdbc:ucanaccess://src/database/DB.accdb";
// Declareren
public static String strAntwoord1;
public void Connect(){
// Initialiseren
Connection con;
Statement s;
ResultSet rs = null;
// Try Database Path/Connection to get Variables
try {
con = DriverManager.getConnection(DB);
s = con.createStatement();
rs = s.executeQuery("SELECT * FROM tblAntwoorden WITH ID=1");
if (rs != null) while ( rs.next() ) {
strAntwoord1 = rs.getString("Antwoord");
if (strAntwoord1 == "Indonesiƫ"){
System.out.println("Antwoord found.");
}
}
s.close();
con.close();
} catch (SQLException e) {
System.out.println("Error: " + e);
}
}
}
It's a task for school and I've got to solve this before midnight. So I've got 1 hour left. Thanks in advance for the people who are willing to help me.
Benji, your SQL has to be perfectioned. Not WITH but WHERE:
SELECT * FROM tblAntwoorden WHERE ID=1
The message says "an alias declaration is expected", e.g.,
SELECT * FROM tblAntwoorden AS a WHERE a.ID=1
yet I hope this suggestion from a different timezone helps you to do the next homework.
I'm facing the problem with this exception java.sql.SQLException: Exhausted Resultset in following code. I'm sure my query returns only one value. Even If I don't use rs.next(); it throws the error java.sql.SQLException: ResultSet.next was not called. Could you please help?
FYI, I'm using the another result set in main where this menthod from another class is called. will it affect?
Thanks
public static String getdispname(Connection conn, String resname)
throws SQLException, Exception {
//String resname = "";
String returnValue = "";
String querystring = "";
//Query to select the displayname from resid
querystring += "select distinct display_name";
querystring += " from cust_rally_team_member";
querystring += " where display_name like '%"+ resid +"%'";
// Create select statement
Statement stmt = conn.createStatement();
try {
// Execute statement
ResultSet rs = stmt.executeQuery(querystring);
if (rs!= null) {
while (rs.next()) {
returnValue = rs.getString("display_name");
} catch (SQLException ex) {
throw new SQLException(ex);
} catch (Exception ex) {
throw new Exception(ex);
}
// Close statement
finally {
stmt.close();
}
return returnValue;
Try as
if (rs! = null) {
while (rs.next()) {
returnValue = rs.getString("display_name");
}
......
Try:
returnValue = rs.next() ? rs.getString("display_name") : null;
You don't need to check if the rs is null. It won't be - assuming the executeQuery() returned rather than raising an exception. (Though the returned result set might have 0 rows).
You also don't need to loop over the result set, assuming you really know that you expect back a single row. (Though, given the query, that seems unlikely.)
use by your modification like below
if (rs != null && rs.first()) {
do {
returnValue = rs.getString(("display_name");
} while (rs.next());
}
I am using Oracle 10g database , i found same error "java.sql.SQLException: Exhausted Resultset error". I just grant permission in database and solved my probblem.
SQL> grant insert,update,delete on "table-name" to "database_name";
I am executing a block of code where I need to retrieve a set of users from database and do some stuff with them. Very simple scenario.
The problem is that although I use while(rs.next()) , when rs.next() reaches null my program tries to continue with the code inside while clause and exits with Null Exception.
Why is that happening? Is something broken in my code that I cannot figure out?
Please, notice that rs is never null. At the beginning prints at the console all the contents of rs but when it reaches the end it returns null exception.
try {
String sql = "select distinct userid from userinfo";
stmt1 = conn.createStatement();
try (ResultSet rs = stmt1.executeQuery(sql)) {
while (rs.next()) {
String mentionsIDs = (rs.getString("mentions")).trim();
try{
if (!mentionsIDs.isEmpty() ){
System.out.println(mentionsIDs);
String[] arr = mentionsIDs.split("\\s+");
if(isNumeric(arr[0])){
System.out.println(arr[0]);
sources.add(Long.parseLong(arr[0]));
}
}
}
catch(Exception ex){
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
rs.close();
}
Any help is appreciated.
Move String mentionsIDs = (rs.getString("mentions")).trim(); inside the try block then catch NullPointerException.
You must also check that the result set indeed have some results in it. Put a condition over your while loop which checks that rs is not null.
if(rs!=null) {
while(rs.next()) {
... Process
}
} else {
System.out.println("The query returned 0 results");
}
In your code:
String sql = "select distinct userid from userinfo";
stmt1 = conn.createStatement();
try (ResultSet rs = stmt1.executeQuery(sql)) {
if(rs!=null) {
while (rs.next()){
String mentionsIDs = (rs.getString("mentions")).trim();
try{
if (!mentionsIDs.isEmpty() ){
System.out.println(mentionsIDs);
String[] arr = mentionsIDs.split("\\s+");
if(isNumeric(arr[0])){
System.out.println(arr[0]);
sources.add(Long.parseLong(arr[0]));
}
}
}
catch(Exception ex){
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
rs.close();
}
so I am a beginer in JDBC - SQL Programming. I need a little advice which is most probably about SYNTAX.
So, Problem = I'm trying to search a record which has name(string provided in function argument) in the record. Following is my code. Now I've designed this code in such a way that there can be more than 1 records with the same name, so all of that records' data will be printed (by ShowData() Function).
protected static void SearchbyName (String toCompareName)
{
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
boolean flag = false; //to confirm if record has found atleast once
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT idEmployee FROM employee WHERE name = ' "+toCompareName+" ' ");
if( !(rs.next()) ) //if ResultSet is not empty
{
while(rs.next()) //reading all records with the same name, extracted by Query
{
int foundID = rs.getInt("idEmployee"); //extracting ID of found record
ShowRecord(foundID); //prints record of foundID fromDB
flag = true; //set flag
}
}
if(flag==false) //if no record found
{
JOptionPane.showMessageDialog(null, "ERROR:: No Records Found..", "Not Found", JOptionPane.ERROR_MESSAGE);
}
//close connection
if(rs!=null)
{ rs.close(); }
if(stmt!=null)
{ stmt.close(); }
if(conn!=null)
{ conn.close(); }
}
catch(SQLException e)
{ System.err.println(e); }
catch(Exception e)
{ System.err.println(e); }
}
So here it is. As far as my understanding goes, there is some problem with either RESULTSET rs or the Query I'm executing.
Kindly help. & if you can suggest a better approach for search, sure do please. I'm going to write 4 more functions SearchbyAge, SearchbyQualification, SearchbySpecialization on the same pattern.
Just this is enough
while(rs.next()) //reading all records with the same name, extracted by Query
{
int foundID = rs.getInt("idEmployee"); //extracting ID of found record
ShowRecord(foundID); //prints record of foundID fromDB
flag = true; //set flag
}
You don't have to check the data in resultset this way with a if case
if( !(rs.next()) )
This will move to the next record in the resultset
SOVLED
My error was in query. I was putting spaces in string's syntax which I was comparing.
WRONG = `"(.. WHERE name = " ' +toCompareName+ '" ");
RIGHT = `"(.. WHERE name = "'+toCompareName+'" ");
So thats it. Hope it helps to anyone else. :)