Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
so I'm trying to connect to a database using java.. there's a problem at a function I wrote getOutSymptoms.
Here's the code
package database_console;
import java.sql.*;
public class DBConnect {
private Connection con;
private Statement st;
private ResultSet rs;
public DBConnect(){
try {
Class.forName("com.mysql.jdbc.Driver");
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users", "root", "admin");
st = con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getOutSymptoms(int userID) throws SQLException{
String query = "SELECT `user`.`out_symptoms` FROM user WHERE (`user`.`id` =" + userID + ")";
rs = st.executeQuery(query);
int out_symptoms_value = rs.getInt("out_symptoms");
st.close();
return out_symptoms_value;
}
the error is at the getOutSymptoms function, at the line:
int out_symptoms_value = rs.getInt("out_symptoms");
why is that? and how can I fix it?
thank u so much.
You need to iterate through your result set in order to get the returned rows. When you first get your new ResultSet, it's not pointing to any particular row (its pointer is set to a row before first) and you need to call rs.next() method at least once to get to the actual results.
If you know there can be only one result you can do something like this:
if (rs.next()) {
int out_symptoms_value = rs.getInt("out_symptoms");
//do other stuff
} else {
//query returned no results
}
If you expect to have more than one row returned, then you can do this:
while(rs.next()) {
int out_symptoms_value = rs.getInt("out_symptoms");
//do the rest of processing
}
TLDR: You need to call rs.next() at least once to get to the actual results.
In order to start using a ResultSet, you must call the next() method. Although you haven't stated the exact error, you will definitely run into this problem unless it is added before you call getInt().
http://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html
you need to iterate through the resultSet object using rs.next() to get the value. resultSet doesn't point to the actual row but when you call rs.next() it points to first result.
while(rs.next(){
int d = rs.getInt(" ");
}
rs.next() returns a boolean value , incase nothing is returned the loop will not execute & you will not get an Exception at runtime.
You have already passed the database name in connection string so change this
String query = "SELECT `user`.`out_symptoms` FROM user WHERE (`user`.`id` =" + userID + ")";
to
String query = "SELECT out_symptoms FROM tableName WHERE id =" + userID;
Then just iterate over the obtained ResultSet like this
while(rs.next()) {
int out_symptoms_value = rs.getInt("out_symptoms");
}
Moreover its good to use PreparedStatement instead of Statement which cna prevent you from sql injection
Related
I am having a problem with a ResultSet being closed. What confuses me is that it works for a portion of the data and then closes. At first I thought it might be because of connection timeout but that doesn't seem the case.
This portion of the program pertains to comparing an .xlsx workbook to an already present SQL database and for lack of a better term merges/updates it.
First, in my CompareDatabase class I am calling a search function that searches an SQLite database for a specific string every 6 iterations.
int columnCount = 6;
dataPoint = dataPoint.replaceAll("Detail", "");
String[] temp = dataPoint.trim().split("\\s+");
System.out.println(Arrays.toString(temp));
for (String tempDataPoint : temp) {
if ( columnCount == 6) {
System.out.println(search(tempDataPoint, connection));
}
columnCount = 0;
} else {
columnCount++;
}
}
This search function (also in the CompareDatabase class is then supposed to search for the value and return a String (was originally a Boolean but I wanted to see the output).
private String search (String searchValue, Connection connection) throws SQLException {
PreparedStatement pStatement = null;
pStatement = connection.prepareStatement("SELECT * FROM lotdatabase where (Vehicle) = (?)");
pStatement.setString(1, searchValue);
try (ResultSet resultSet = pStatement.executeQuery()){
return resultSet.getString(1);
}finally {
close(pStatement);
}
}
At the end you can see that the PreparedStatement is closed. The ResultSet should also be closed automatically (I read somewhere) but JDBC could possibly be being unreliable.
The Connection however is still open as it will be searching some 200+ strings and opening and closing that many times did not seem like a good idea.
These functions are called by my main class here:
One is commented out since it will error out because of primary key violation.
public static void main(String[] args) {
SQLDatabase sqlDatabase = new SQLDatabase();
//sqlDatabase.convertToSQL("Database1.xlsx");
sqlDatabase.compare("Database2.xlsx");
}
I have a suspicion that I am going about a bunch of this wrong (on the aspect of managing connections an such) and I would appreciate a reference to where I can learn to do it properly.
Also, being that PreparedStatement can only handle one ResultSet I don't see that being my issue since I close it every iteration in the for loop.
If more code or explanation is required please let me know and I will do my best to assist.
Thank you for taking the time to read this.
So after a bit more Googling and sleeping on it here is what worked for me.
The search function in compareDatabase changed to this:
private Boolean search (String searchValue, Connection connection) {
PreparedStatement ps = null;
try {
ps = connection.prepareStatement("SELECT * FROM lotdatabase where " +
"(Vehicle) = (?)");
ps.setString(1, searchValue);
ResultSet resultSet = ps.executeQuery();
//The following if statement checks if the ResultSet is empty.
if (!resultSet.next()){
resultSet.close();
ps.close();
return false;
}else{
resultSet.close();
ps.close();
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
And in the other function within compareDatabase I call the search function like this:
if (search(tempDataPoint, connection)) {
System.out.println("MATCH FOUND: " + tempDataPoint);
}else {
System.out.println("NOT FOUND: " + tempDataPoint);
}
This allows me to check the ResultSet and also be sure that it is closed.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I ran in to a problem while trying to get data from my sql server where they give a null point exception at prepared statement. I'm sure this must be a noob question but please do help :)
this is the method i'm calling
public void notification(){
int MachCode = 1721;
try{
String sql ="Select TimeOn from PRODUCTIONS_MONITOR where MachCode='"+MachCode+"'";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
arrCount.add(rs.getInt(1));
}
for(int i=0;i<arrCount.size();i++){
Count = Count + arrCount.get(i);
}
if(Count % 10 == 0){
System.out.println("Time = " + Count);
}
}catch(SQLException e){
e.printStackTrace();
}
}
and here is my db connection
public static Connection ConnecrDb() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://10.228.59.2:1433;databaseName=dbNautilus;user=SA;password=KreedaIntimo#2017;");
System.out.println("Connected to database !");
} catch (SQLException sqle) {
System.out.println("Sql Exception :" + sqle.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found Exception :" + e.getMessage());
}
return null;
}
Your ConnecrDb() method assigns the new Connection object to a local variable named con, and then never use it.
The method then returns null.
You didn't show how to method was called, but it really doesn't matter, because the con field used by notification() method is either unassigned (and hence null), or assigned the null return value from ConnecrDb(), so it is null either way.
Given that, why are you confused the value is null and causes a NullPointerException?
Other general comment about your code:
If MachCode is an integer, then why are you quoting it in SQL, i.e. why where MachCode='"+MachCode+"'"; and not where MachCode="+MachCode;?
If you're using PreparedStatement, why not use ? parameter markers, as they are intended to be used?
You should use try-with-resources when using JDBC.
Java naming convention is for variable names to start with lowercase letter.
Your code should be:
int machCode = 1721;
String sql = "select TimeOn from PRODUCTIONS_MONITOR where MachCode = ?";
try (PreparedStatement pst = con.prepareStatement(sql)) {
pst.setInt(1, machCode);
try (ResultSet rs = pst.executeQuery()) {
while (rs.next()) {
arrCount.add(rs.getInt(1));
}
}
}
// rest of code here
I am working on a JAVA program which need to update database from text files. I have successfully inserted and updated data. But i am facing a problem with here, this method. Query runs without error and giving me the response. But the database table is not updating.
private void filteData() {
System.out.println("filteData");
Statement statementAtenLogInsert = null;
Statement statementqCheck = null;
Statement statementUpdateProLog = null;
Statement statementEnterError = null;
ResultSet rs = null;
int rcount;
//Update successfull attendance_test
String attenLogInsertSuccess = "INSERT INTO attendance_log (user_id, check_in, check_out) SELECT user_id, check_in, check_out FROM process_log WHERE flag = 'S'";
try {
statementAtenLogInsert = connection.createStatement();
statementAtenLogInsert.execute(attenLogInsertSuccess);
int qSuccess = statementAtenLogInsert.executeUpdate(attenLogInsertSuccess);
System.out.println("qSuccess " + qSuccess);
if(qSuccess > 0){
String deleteProcessLog = "DELETE FROM process_log WHERE flag = 'S'";
statementAtenLogInsert.execute(deleteProcessLog);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here the attenLogInsertSuccess and deleteProcessLog queries are not working. Mean nothing happened from database table side. But qSuccess giving me a value. That means attenLogInsertSuccess is triggering. But nothing happened from mysql side.
You need to close your connection in order to flush the changes to the database.
Try adding connection.close(); somewhere in your pipeline, typically you close the connection in a finally block to ensure it is always closed but it appears you have defined your connection elsewhere, presumably for re-use in the calling function.
You also need to close your statements before closing the connection. See this similar answer for the pattern.
private void btgetinvActionPerformed(java.awt.event.ActionEvent evt) {
//JOptionPane.showMessageDialog(null, "REMITTANCE ID IS VALID!");
try {
DBUtil util = new DBUtil();
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement("select bk_det.rm_id from bk_det WHERE dbo.bk_det.rm_id = ?");
ResultSet rs;
String rm = tf_rmid.getText().trim();
stmt.setInt(1, Integer.parseInt(rm));
rs = stmt.executeQuery();
while (rs.next()) {
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
I am actually trying to search value from my database table called dbo.bk_det. I am taking the value of WHERE from my textfield tf_rmid. Everything goes on well without error but once i insert the rm_id and click on button btgetinv it says 123 which is my rm_id is out of range cant understand where the error is and what is the problem.
The problem is with the following statements:
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
The first statement won't work the way you want because there's no column named "box_no" in the select clause. It will throw an exception. Let's assume you change the code to have box_no in the select clause. Then, the second statement will try to retrieve the nth column where the column is the value of box_no. I think you just want:
tfbrname.setText(rs.getString("box_no"));
Again, the above only will work if your SELECT statement includes box_no in the field list.
rs.next() returns false if it does not contain any more records. So if you want to behave something when no records found, you have to check record count.
for example,
int recordCount = 0;
while (rs.next()) {
recordCount++;
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
}
if(recordCount == 0) {
// do something : report an error or log
}
for further information, see http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#next()
I write a opration on java soap service to query the database and then show the data I have searched on client jsp page. However, I can't show it, the variable "rs" cannot change, I don't know why? could someone help me to find the troboule?
This is the opration i create on soap service:
#WebMethod(operationName = "query")
public String query(#WebParam(name = "parameter") String parameter) {
ResultSet rs;
try {
Connection con = data1.getConnection();
Statement statement = con.createStatement();
String QueryString;
QueryString = "SELECT * from stud where name= parameter";
rs = statement.executeQuery(QueryString);
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + "\n");
}
} catch (Exception ex) {
System.out.println("Unable to connect to batabase.");//TODO write your implementation code here:
}
//TODO write your implementation code here:
return null;
}
I'm not totally sure I understand your question. Maybe you mean that you can view the console output and this process that rs is an empty result set. You said rs cannot change, but you probable realize that rs stores the entire result set and you only assign it once, so it doesn't "change" if your code is working currently.
One obvious thing that is wrong is that parameter is a variable (in fact, a parameter!) But you include it inside the quotes as part of the query string. So regardless if the function input, you are searching the database for the name "parameter"