I'm trying to read string values from my database to insert them in an arraylist of strings. However, my loop stops after completing only one row.
That's my code,
public void initialize(URL arg0, ResourceBundle arg1) {
Statement stmt = null;
String query = "SELECT CustomerName FROM CUSTOMER WHERE CustomerName IS NOT NULL";
try {
Connection conn1 = DBConnection.getConnection();
stmt = conn1.createStatement();
ResultSet rs = stmt.executeQuery(query);
// iterate through the java resultset
while (rs.next()) {
System.out.println(rs.getString("CustomerName"));
customersnames.add(rs.getString("CustomerName"));
}
stmt.close();
} catch (Exception e) {
System.out.println("Exception at initialize ");
System.err.println(e.getMessage());
}
try {
TextFields.bindAutoCompletion(customer, customersnames);
} catch (NullPointerException E) {
}
}
and that's what I'm getting
null (that's in red)
heee
Exception at initialize
"heee" is the first row of my database, but I have many more, that's what it's reading only and it's throwing an exception.
Apparently, you get a NullPointerException after having printed the result of the first row.
Did you initialize your object customersnames?
In order to be sure, change System.err.println(e.getMessage()); into e.printStackTrace()
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 wrote some java code to display database, when I run the code it gives me just the last element of database , but I wanna display all elements of table
the code :
public String RecupererPuissance() {
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
puissance=rs.getString("Power");
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissance;
}
What should I do? Can anyone please help me to display all values?
Thank you for helping me.
I think the problem is with your code that the value of puissance is overwritten every time you get the next element. Only the last value is returned. You should put the results into a list and return the whole list:
public List<String> RecupererPuissance() {
List<String> puissances = new ArrayList<String>();
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
puissance = rs.getString("Power");
puissances.add(puissance);
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissances;
}
public String RecupererPuissance() {
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
rs.first();
int count=0;
while (rs.next()) {
System.out.println("count = "+count);
count+=1;
puissance=rs.getString("Power");
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissance;
}
If you see count printed only 1 time :
it would mean that you have only 1 row in column Power
and you maybe referring to the wrong column in your code
I am building an application in which you can save deals to database. I'd like to search deals in my database and populate my jtable with relevant results. I want to query my database on keyrelease event. I know it is not an efficient method but I am curious why I can't get it to work.
Below is a sample code that tries to query a database table with ID and country names. There are only 3 country names that start with "D". Somehow I can get country names printed out but can't get them to populate jtable.
The error -
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" I can't get ResultSet rs1 into a Object[][] . It works fine if I do System.out.println(rs1.getString("Name")
Below is the code -
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
String columnName[] = new String[] { "Name" };
Object oss[][] = new Object[3][];
ResultSet rs1 = null;
int li = 0;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection con = DriverManager.getConnection(Url, User, Password);
Statement st = con.createStatement();
String query = "SELECT * from unit.cntry WHERE Name LIKE '" + abc.getText() + "%';";
rs1 = st.executeQuery(query);
} catch (Exception e) {}
try {
while (rs1.next()) {
oss[li][0] = rs1.getString("Name");
li++;
}
myTable.setModel(new DefaultTableModel(oss, columnName));
} catch (SQLException ex) {
System.out.println(ex.toString());
} finally {
try {
if (rs1 != null) rs1.close();
} catch (SQLException e) {}
}
}
oss[li] = new Object[1];
oss[li][0] = rs1.getString("Name");
Other data structures might be more appealing.
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();
}
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.