Observing a strange behavior of this piece of code,because resultset is not giving the null value(doing SOP it's clear)but not going into while loop(that is quite strange!)and it's simple dao class,it's not able to set the value in user object:
public class DAO{
public List<User> searchAllUsers(int offset ,int noOfRecords, String column, String value){
String query="select SQL_CALC_FOUND_ROWS * from info where '"+column+"' like '%"+value+"%' order by serialNo asc limit " + offset + " , " + noOfRecords;
// String query="select * from info where '"+select+"' like '%"+search+"%' order by serialNo asc";
System.out.println("1");
List<User> list = new ArrayList<User>();
User user=null;
try {
System.out.println("b4 Connection");
connection = getConnection();
System.out.println("After Connection");
stmt = connection.createStatement();
System.out.println("Create statement");
ResultSet rs=stmt.executeQuery(query);
if(rs!=null)
System.out.println("1> Hi rs:"+rs);
while(rs!= null && rs.next()){
System.out.println("hi...!!");
user=new User();
user.setSerial(rs.getInt(1));
System.out.println("Serial : "+rs.getInt(1));
user.setName(rs.getString(2));
user.setEmail(rs.getString(3));
user.setImei(rs.getString(4));
System.out.println("I'm here !");
user.setModel(rs.getString(5));
user.setManufacturer(rs.getString(6));
user.setOsversion(rs.getString(7));
user.setHdyk(rs.getString(8));
user.setDate(rs.getString(9));
user.setAppname(rs.getString(10));
list.add(user);
System.out.println("Last..");
}
rs.close();
rs = stmt.executeQuery("SELECT FOUND_ROWS()");
System.out.println("2> :" +rs);
if(rs.next()){
this.noOfRecords = rs.getInt(1);
System.out.println("3> :" +this.noOfRecords);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
finally
{
try {
if(stmt != null)
stmt.close();
if(connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
public int getNoOfRecords() {
return noOfRecords;
}
}
And it corresponding output is :
1
b4 Connection
After Connection
Create statement
1> Hi rs:com.mysql.jdbc.JDBC4ResultSet#35e6e3
2> :com.mysql.jdbc.JDBC4ResultSet#c9630a
3> :0
Even I'm also using the same code like it for select All user's and that point of time I'm getting proper o/p.
Spending so many hours for it,but unable to resolve it-where I'm going wrong....so your review & comment will be always welcome.
That's because your query didn't fetch you any row. And hence rs.next() will return false, hence the execution will not go into the while loop:
while(rs!= null && rs.next())
And you don't have to check for rs != null. It won't be null. The stmt.executeQuery always returns a ResultSet. Just have rs.next() in your while:
while(rs.next())
And yes, you should use PreparedStatement for executing your query rather than Statement. Here's a tutorial which will help you get started.
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 need to get the output of a jdbc query, but wherever I google, it returns a resultset. But, its just a single row. Here is my query
ResultSet rsLocationId = null;
rsLocationId = stmtLocation.executeQuery("SELECT apmcid FROM userbusinesstoapmc WHERE userbusinessid='"+userBusinessKey+"'");
It should return a single record as a string. How can I convert it? Any ideas would be greatly appreciated.
I suggest you use PreparedStatement and bind the parameter, currently you are vulnerable to SQL Injection attacks.
PreparedStatement ps = null;
ResultSet rs = null;
String result = null;
final String sql = "SELECT apmcid FROM userbusinesstoapmc "
+ "WHERE userbusinessid=?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, userBusinessKey);
rs = ps.executeQuery();
if (rs.next()) {
result = rs.getString("apmcid");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
you can try like this
ResultSet rsLocationId = null;String result="";
rsLocationId = stmtLocation.executeQuery("SELECT apmcid FROM userbusinesstoapmc WHERE userbusinessid='"+userBusinessKey+"'");
if(rsLocationId.next())
{
result=rsLocationId.getString('apmcid');
}
Even though your particular query only returns a single column, presumably some CHAR type if you expect the result to be a String, the executeQuery method returns a result set object, not a String object. So, you have to process the result set to get your String data. SpringLearner has provided a good example of how to do this.
I'm trying to get a specifc customer id out of a MySQL table from a telephone number input from the user to use it to add a new order to that customer id. I'm trying to use a method that creates a list being filled by resultset but I keep being returned nothing, more specificly empty square brackets "[]"
This is the code im using.
if((getCustomerID.getCustomerID(inputContactNumber).toString()).equals("[]")){
JOptionPane.showMessageDialog(null, "Customer phone number does not exist.\nTry again or create new customer.");
return;
} else {
customerID = Integer.parseInt(getCustomerID.getCustomerID(inputContactNumber).toString());
insertOrder.insertOrder(customerID);
}
getCustomerID():
public List<Customer> getCustomerID(String phoneNumber) throws SQLException{
List<Customer> customerList = new ArrayList();
String selectCustomerID = "SELECT idcustomer FROM customer WHERE contactNumber = " + phoneNumber;
try {
MyConnection mc = new MyConnection();
dbConnection = mc.getConnection();
statement = dbConnection.createStatement();
ResultSet rs = statement.executeQuery(selectCustomerID);
while (rs.next()){
int customerID = rs.getInt("idcustomer");
Customer c;
c = new Customer (customerID);
customerList.add(c);
}
}
catch (SQLException e){
System.err.println(e);
return null;
}
finally{
if (statement != null){
statement.close();
}
if (dbConnection != null){
dbConnection.close();
}
}
return customerList;
}//end of getGetCustomerID()
Any input is greatly appreciated
-Edit-
MyConnection()
public class MyConnection {
public Connection connection = null;
public Connection getConnection()
{
System.out.println("---- MySql Connecting ----");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Can't find MySQl Driver.");
e.printStackTrace();
}
System.out.println("Driver Registered.");
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/quotedb","root","");
} catch (SQLException e) {
System.out.println("Connection Failed.");
}
if (connection != null) {
System.out.println("Connection Established.");
} else {
System.out.println("Connection Failed.");
}
return connection ;
}
Have you tried executing this query in a SQL Programm? As it looks like simply no result is returned, thus the empty square brackets which is the String equivalent of an empty Array.
toString() on an Array is generally a bad idea, you better use length to determine if the Array is empty. Furthermore it is not clear if the result should be unique or not:
If the function getCustomerID.getCustomerID(inputContactNumber) returns more than one result you try to parse a Int like [3453,3543] which will never be what you want. Instead you should use .get(0) on the Array to retrieve the first element.
Please change your select query to
"SELECT idcustomer FROM customer WHERE contactNumber = '"+phoneNumber+"'"
it will work fine i hope
Change the if condition to:
if(getCustomerID(inputContactNumber) == null || getCustomerID(inputContactNumber).isEmpty()){
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. :)