Error while getting resultset - java

I have a class in which i am getting resultset from the database:
public ResultSet GetDataFromDB() {
ResultSet resultset = null;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
System.out.println("Connecting to the database...");
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:#host:1521:DBname", "user123","pass123");
Statement statement = connection.createStatement();
resultset = statement.executeQuery("select * from tablename");
while (resultset.next()) {
System.out.println(resultset.getInt(1) + " " +
resultset.getInt(2) + " " +
resultset.getInt(3) + " " +
resultset.getString(4));
}
// statement.close();
//connection.close();
} catch (Exception e) {
System.out.println("The exception raised is:" + e);
}
return resultset;
}
In this classs i am able to print the data which i am getting in resultset. but when i tried to get this resultset in another class:
Classname obj= new Classname();
ResultSet tempResultSet = obj.GetDataFromDB();
System.out.println("Records Exist "+tempResultSet.next()); <-----false
I am not getting any data here.
also there is no datatable here in java like in .net so that i can use that...Please concern
thanks

while (resultset.next()) {
You already read all of the data from the ResultSet in this loop.
ResultSet is a single-use, forward-only view of the data; you can only iterate it once.

Related

I got data from MySQL to show up in the jTable but I'm getting an Exception

Here's the code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String PatientID = jtxtPatientID.getText();
try {
Connection con = ConnectionProvider.getCon();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select *from patient where PatientID='" + PatientID + "'");
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
while(rs.first()){
jlbPID.setVisible(false);
jtxtPatientID.setEditable(false);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Connection Error");
}
}
My code is going to the catch block, but I don't know why.
First of all, answering your question, your problem is that "select *from patient where PatientID='" + PatientID + "'" is not a valid SQLstatement, because the * and the FROM clause are together. Instead, add a space on it.
Just change:
ResultSet rs = st.executeQuery("select *from patient where PatientID='" + PatientID + "'");
with:
ResultSet rs = st.executeQuery("select * from patient where PatientID='" + PatientID + "'");
And, as a side note, just a mere recommendation: Don't use the Statement interface if your SQL has parameters, instead, use the PreparedStatement interface. Otherwise, your code will be vulnerable to SQL Injection.
And, please, change your catch blocks to someting which is able to log what's happening on your application. It will help you a lot when debugging. What I recommend you is, basically, this:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
private static final Logger LOG = LogManager.getLogger(Myclass.class);
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String PatientID = jtxtPatientID.getText();
String sql = "select * from patient where PatientID=?";
try {
Connection con = ConnectionProvider.getCon();
PreparedStatement st = con.prepareStatement(sql);
st.setString(1, PatientID);
ResultSet rs = st.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
while(rs.first()){
jlbPID.setVisible(false);
jtxtPatientID.setEditable(false);
}
} catch (SQLException e) {
LOG.error("Error while processing the SQL statement...", e);
JOptionPane.showMessageDialog(null, "Connection Error");
}
}
I used log4j2 for the logging purposes of this example.

Java ResultSet Skipping Records

After a morning of research, I'm stumped on what should be an easy piece of code.
All I want is to get all records from our raw_material table in the test database.
Here is what I am doing:
public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
// TODO Auto-generated method stub
//get our stuff first - raw materials and doc names and paths
try {
Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0");
do {
String result = rs.getString("raw_material_number").toString();
System.out.println("next item: " + result);
//ithosList.add(rs.getString("raw_material_number"));
} while(rs.next());
}
catch (Exception e) {
ithosList.equals(null);
System.out.println("DB error : " + e);
}
}
Here are the results in mySQL:
so I would expect the first 'result' to be MAN-500-121200000, but it is showing as RAW-001485
I cannot see anywhere in the code that I am 'skipping' the first record, but if I let it go, it will skip the next one to MAN-500-056100000
Am I using the wrong user connection? That is the only thing I can see that affects this.
I thought user.getConnection() would do it for just the regular test database.
Your code seems to be incorrect, the expected loop is rather:
while(rs.next()) {
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
}
Consider using try-with-resources statement to close properly your Connection, Statement and ResultSet as next:
try (Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0")) {
// My code here
}
Try like this.
while(rs.next()){
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
}
public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
// TODO Auto-generated method stub
int i = 1;
//get our stuff first - raw materials and doc names and paths
try {
Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rsCount = st.executeQuery("SELECT COUNT(*) from raw_material");
rsCount.first();
long r = (Long) rsCount.getObject(i);
for (i=1; i < r+1; i++) {
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id =" + i + "");
//moves to the first record
rs.first();
do {
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
ithosList.add(rs.getString("raw_material_number"));
} while(rs.next());
}
}
catch (Exception e) {
ithosList.equals(null);
System.out.println("DB error : " + e);
}
}
Hacky way of doing it but it got it to work for now, at least until the senior developer returns from bereavement. Keep in mind I've had only 3 months of java, baptism by fire. lol.

MySQLSyntaxErrorException in SQL syntax

I am trying to select data from a table using prepared statement. But it seems like I am getting syntax error which I cannot solve alone.
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String dbusername = "root";
String dbpassword = ""; // Change it to your Password
// Setup the connection with the DB
connection = DriverManager.getConnection(url, dbusername,
dbpassword);
String query = "SELECT * FROM admin WHERE username = ? AND password = ?";
try {
// connection.setAutoCommit(false);
selectUser = connection.prepareStatement(query);
selectUser.setString(1, username);
selectUser.setString(2, password);
// Execute preparedstatement
ResultSet rs = selectUser.executeQuery(query);
// Output user details and query
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: " + query);
boolean more = rs.next();
// if user does not exist set the validity variable to true
if (!more) {
System.out
.println("Sorry, you are not a registered user! Please sign up first!");
user.setValid(false);
}
// if user exists set the validity variable to true
else if (more) {
String name = rs.getString("name");
System.out.println("Welcome " + name);
user.setName(name);
user.setValid(true);
}
} catch (Exception e) {
System.out.println("Prepared Statement Error! " + e);
}
} catch (Exception e) {
System.out.println("Log in failed: An exception has occured! " + e);
} finally {
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
System.out.println("Connection closing exception occured! ");
}
connection = null;
}
return user;
}
I get following error.
Prepared Statement Error! com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '? AND password = ?' at line 1
But I don't see any error in that code line.
Change
ResultSet rs = selectUser.executeQuery(query);
to
ResultSet rs = selectUser.executeQuery();
when you already prepared the statement in connection.prepareStatement(query); then why to pass the query again in selectUser.executeQuery(query);
what you want to do is use this method
ResultSet rs = selectUser.executeQuery();
You have already loaded your query inside the prepared statement here ,
selectUser = connection.prepareStatement(query);
so execute it by ,
ResultSet rs = selectUser.executeQuery();
Also read ,
How does PreparedStatement.executeQuery work?

PSQLException thrown when trying to execute SELECT query

I have problem with my SQL request, when I run my request, I receive this message error:
org.postgresql.util.PSQLException: A result was returned when none was expected.
Here is my request:
Connexion con = new Connexion();
try {
c = con.Connect();
stmt = c.createStatement();
int sqlCalcul = stmt.executeUpdate(
"SELECT inventaire FROM calcul WHERE designation='" + designation +
"' AND date=(SELECT MAX(date) FROM calcul)");
stmt.close();
// c.commit();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Records created successfully");
You should use executeQuery instead of executeUpdate:
ResultSet sqlCalcul = stmt.executeQuery("SELECT inventaire...")
executeUpdate is used for a INSERT, UPDATE, or DELETE statement, and will throw an exception if a ResultSet is returned. executeQuery should be used for SELECT statements.
Take a look at PostgreSQL's tutorial using the JDBC driver for more information.

Java prepared statement in try-with-resources not working [duplicate]

This question already has answers here:
How should I use try-with-resources with JDBC?
(5 answers)
Closed 8 years ago.
Yesterday multiple people on Stack recommended using try-with-resources. I am doing this for all my database operations now. Today I wanted to change Statement to PreparedStatement to make the queries more secure. But when I try to use a prepared statement in try-with-resources I keep getting errors like 'identifier expected' or ';' or ')'.
What am I doing wrong? Or isnt this possible? This is my code:
try (Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
PreparedStatement stmt = conn.prepareStatement("SELECT id FROM users WHERE id = ? LIMIT 1");
stmt.setInt(1, user);
ResultSet rs = stmt.executeQuery()) {
// if no record found
if(!rs.isBeforeFirst()) {
return false;
}
// if record found
else {
return true;
}
} catch (SQLException e) {
// log error but dont do anything, maybe later
String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
return false;
}
A try-with-resource statement is used to declare (Autoclosable) resources. Connection, PreparedStatement and ResultSet are Autoclosable, so that's fine.
But stmt.setInt(1, user) is NOT a resource, but a simple statement. You cannot have simple statements (that are no resource declarations) within a try-with-resource statement!
Solution: Create multiple try-with-resource statements!
try (Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS)) {
executeStatement(conn);
} catch (SQLException e) {
// log error but dont do anything, maybe later
String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
return false;
}
private void executeStatement(Connection con) throws SQLException {
try (PreparedStatement stmt = conn.prepareStatement("SELECT id FROM users WHERE id=? LIMIT 1")) {
stmt.setInt(1, user);
try (ResultSet rs = stmt.executeQuery()) {
// process result
}
}
}
(Please note that technically it is not required to put the execution of the SQL statement into a separate method as I did. It also works if both, opening the connection and creating the PreparedStatement are within the same try-with-resource statement. I just consider it good practice to separate connection management stuff from the rest of the code).
try this code:
try (Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS)) {
PreparedStatement stmt = conn.prepareStatement("SELECT id FROM users WHERE id = ? LIMIT 1");
stmt.setInt(1, user);
ResultSet rs = pstmt.executeQuery())
// if no record found
if(!rs.isBeforeFirst()) {
return false;
}
// if record found
else {
return true;
}
} catch (SQLException e) {
// log error but dont do anything, maybe later
String error = "SQLException: " + e.getMessage() + "\nSQLState: " + e.getSQLState() + "\nVendorError: " + e.getErrorCode();
return false;
}
note that here, resource is your Connection and you have to use it in the try block ()
Move
stmt.setInt(1, user);
ResultSet rs = stmt.executeQuery()
...within the try{ /*HERE*/ }
This is because stmt is the resource being created try (/*HERE*/) {} to be used try{ /*HERE*/ }
Try-with-resources
try (/*Create resources in here such as conn and stmt*/)
{
//Use the resources created above such as stmt
}
The point being that everything created in the resource creation block implements AutoClosable and when the try block is exited, close() is called on them all.
In your code stmt.setInt(1, user); is not an AutoCloseable resource, hence the problem.

Categories

Resources