Can't select data from MySQL database: java.lang.NullPointerException - java

I'm trying to select data from database using this code:
//DATABASE
ResultSet rs;
String polecenie;
Statement st;
String[] subj;
public void polacz() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection pol=DriverManager.getConnection("jdbc:mysql://localhost:3306/testgenerator", "root", "pospaz");
st = pol.createStatement();
lblPolaczonoZBaza.setText("Połączono z bazą danych testgenerator");
} catch (Exception ek) {
statusMessageLabel.setText("Can't connect to d: "+ek);
}
polecenie = "select * from subjects";
try {
rs = st.executeQuery(polecenie);
int i=0;
while (rs.next()){
subj[i] = rs.getString("name");
i++;
}
st.close();
} catch (Exception ek) {
statusMessageLabel.setText("Can't select data: "+ek);
}
}
The second catch shows exception:
java.lang.NullPointerException
I looked everywhere and I can't find the solution. I'd be grateful for any help.

You never instantiate subj[] which causes it to be null

You're not initializing the String[] subj array, that I can see, so when it gets to subj[i] = ... it chokes. You need to do one of the following:
determine the number of rows in the resultset, and initialize subj = new String[resultcount]
use an auto-extending container (like an ArrayList) instead of the string array

Related

Getting data From a java DB with SQL Using ResultSet

I created a method to get the values from a database in java using SQL and store the information in a ResultSet and then use a while loop to store the information in a RentSendItem and store all those items in an ArrayList called sendList but when I try to run it, it gives me the error:
'ResultSet not open. Operation 'getString' not permitted. Verify that autocommit is off'
This is my class:
public void getDataFromDB() {
System.out.println("Wordk");
//connecting
Connection connection = null;
Statement statement = null;
try {
System.out.println("1");
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
ResultSet name = statement.executeQuery("SELECT firstname,surname FROM CUSTOMER");
ResultSet titles = statement.executeQuery("Select Title,Category From ADDDVD ");
System.out.println(name.getString("firstname"));
System.out.println("2");
while (name.next()) {
String fullName = name.getString("firstname") + " " + name.getString("surname");
RentSendItem item = new RentSendItem(name.getString("firstname") + name.getString("surname"), titles.getString("Category"), titles.getString("title"));
sendList.add(item);
}
System.out.println("3");
} catch (Exception e) {
System.out.println("Error" + e.getMessage());
}
}
So just want to know what am I doing wrong and will this class do what I want it to do. If you could maybe help me, I would be grateful.
There are several problems in your code.
You can't call method getString() of interface java.sql.ResultSet before you call method next(). First call method next() and if that method returns "true", then you can call method getString().
You also need to call method next() on titles.
You can't call getString() twice on the same column on the same row.
Compare the below with your code.
public void getDataFromDB() {
System.out.println("Wordk");
// connecting
try (Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement()) {
System.out.println("1");
ResultSet name = statement.executeQuery("SELECT firstname,surname FROM CUSTOMER");
ResultSet titles = statement.executeQuery("Select Title,Category From ADDDVD ");
System.out.println("2");
while (name.next()) {
String firstname = name.getString("firstname");
String surname = name.getString("surname");
String fullName = firstname + " " + surname;
if (titles.next()) {
RentSendItem item = new RentSendItem(fullName,
titles.getString("Category"),
titles.getString("title"));
sendList.add(item);
}
}
System.out.println("3");
}
catch (Exception e) {
e.printStackTrace();
}
}
Also, the following are not problems but recommendations.
In the catch block, it usually preferable to print the entire stack trace rather than just the error message.
You should close the Connection and Statement once you no longer need them. In the code above, I have used try-with-resources

Return an ms access column into an array

I'm trying to return a column of scores from a MS Access table using java. This is the table
I followed the guide from the java documentation.This is the result code
public class DatabaseConnector {
public static void main(String[] args){
Connection connection=null;
Statement statement =null;
ResultSet resultSet = null;
//Loads JDBC DRIVER
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
}catch (ClassNotFoundException cnfex){
System.out.println("There was a problem loading MS Access Driver");
cnfex.printStackTrace();
}
//Loads Database
try{
String scoredb="C:/Users/User/"+"/Documents/Database2.accdb";
String mydburl ="jdbc:ucanaccess://"+scoredb;
connection = DriverManager.getConnection(mydburl);
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT CSC103, CSC103 FROM Scores");
while(resultSet.next()) {
Array z = resultSet.getArray("CSC103");
int[] CSC103 = (int[])z.getArray();
for (int i=0;i<CSC103.length;i++){
System.out.println(i);
}
}
} catch (SQLException sqlex){
sqlex.printStackTrace();
}
finally {
try{
if (null != connection) {
resultSet.close();
statement.close();
connection.close();
}
}catch (SQLException sqlex){
sqlex.printStackTrace();
}
}
I ended up getting the error-
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to [Ljava.lang.Object;
at org.hsqldb.jdbc.JDBCResultSet.getArray(Unknown Source)
at org.hsqldb.jdbc.JDBCResultSet.getArray(Unknown Source)
at net.ucanaccess.jdbc.UcanaccessResultSet.getArray(UcanaccessResultSet.java:184)
at DatabaseConnector.main(DatabaseConnector.java:28)
I have taken a look at this error online and it's a bit confusing because the solutions don't apply to database. How do I fix the error and get my values from the column?
ResultSet#getArray is used with databases that support special columns in which we can store an array of values for each row in the table. Access does not have an Array column type. The CSC103 column in your table contains a single ("scalar") value for each row, an integer in this case.
So you need to retrieve the individual values for each row and add them to a collection of some sort. The most straightforward way would be
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT CSC103 FROM Scores");
java.util.List<Integer> csc103List = new java.util.ArrayList<>();
while (rs.next()) {
csc103List.add(rs.getInt("CSC103"));
}
after which you'll have the values in an ArrayList<Integer>. If you really need an array of type Integer (which is a slightly different thing) then you can convert the List into an array like so:
Integer[] csc103Array = csc103List.toArray(new Integer[0]);

Retrieving data from database and increment by one

I am trying to retrieve a data (ID No.) from a database (MySQL) and add it by one. However, when I try to put this code below, when I try to build it, the form doesn't show up. But when I try to remove the Connection cn line, the form with finally show up. I had another project with this code it it worked perfectly fine. I'm not sure why its not working on this one.
public Abstract() throws Exception {
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
initComponents();
Statement st = null;
ResultSet rs;
try {
String sql = "SELECT ID from bidding_abstractofprices";
st = cn.prepareStatement(sql);
rs = st.executeQuery(sql);
while(rs.next()){
int id = Integer.parseInt(rs.getString("ID")) + 1;
lblTransacID.setText(String.valueOf(id));
}
}catch (Exception ex){
}
}
What it looks like you are trying to do is to get the ID field value from the last record contained within the bidding_abstractofprices Table contained within your Database and then increment that ID value by one (please correct me if I'm wrong). I don't care why but I can easily assume. Here is how I might do it:
public Abstract() throws Exception {
// Allow all your components to initialize first.
initComponents();
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
Statement st = null;
ResultSet rs;
try {
String sql = "SELECT * FROM bidding_abstractofprices ORDER BY ID DESC LIMIT 1;";
st = cn.prepareStatement(sql);
rs = st.executeQuery(sql);
int id = 0;
while(rs.next()){
id = rs.getInt("ID") + 1;
}
lblTransacID.setText(String.valueOf(id));
rs.close();
st.close();
cn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}

Printing a query from a database

I am trying to access a database and print off a query.
I am trying to access a DEVICE table and print off the DEVICE_ID, but i am unsuccessful so far.
Here is my code at the moment;
public static void main(String[] args) throws FileNotFoundException {
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
Preferences sysRoot = Preferences.systemRoot();
Preferences prefs = sysRoot.node("com/davranetworks/zebu");
url = prefs.get("dburl", "jdbc:hsqldb:E:\\eem\\eemdb");
} catch (Exception e) {
e.printStackTrace();
}
Connection c = getConnection();
try {
c.setAutoCommit(true);
Statement s = c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = s.executeQuery("SELECT * FROM eem_db.device");
ResultSet deviceId = s.executeQuery("select device_id from eem_db.device");
System.out.println(deviceId);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection c = null;
try {
c = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println("Error initialising connection" + e);
}
return c;
}
The returned value is org.hsqldb.jdbc.JDBCResultSet#1d3d68df.
I don't know what this value relates to as I was expecting 3 integer values.
Can anyone help me on this?
You have to iterate over the rows contained in the ResultSet and for each row get the column you want:
ResultSet deviceIdRS = s.executeQuery("select device_id from eem_db.device");
while(deviceIdRS.next()) {
System.out.println(deviceIdRS.getString("device_id"));
}
You must use the ResultSet getXXX method that correspond with your column type, for example, getInt, getString, getDate...
That ResultSet deviceId is actually an object contains rows of result from your sql, so you only can see the memory address when you print it out.
You need something like:
while(deviceId.next()){
System.out.print(deviceId.getInt(1));
}
s.executeQuery("select device_id from eem_db.device"); is returning a resultSet, you must find out the value from result set.
like
int device_id = resultset["deviceId"];
while (deviceId.next())
{
// Printing results to the console
System.out.println("device_id- "+ deviceId.getInt("device_id");
}
iterate object using resultset.
You are printing object of ResultSet, it won't give you the right values.
You need to iterate the loop like below
while(deviceId.next()) {
int integerValue = deviceId.getInt(1);
System.out.println("content" + integerValue)
}
deviceId.close();
s.close();

Resultset error

Im working with Java EE and derby, i try to get data from my resultset and put them in int and string but don't work it gives me this error :
java.sql.SQLException: Invalid operation for the current cursor location.
i tryed result.next() but nothing, here is my code :
Connection conn = null;
Statement stmt = null;
ResultSet result = null;
Hotel hot = new Hotel();
try {
synchronized (dataSource) {
conn = dataSource.getConnection();
}
stmt = conn.createStatement();
String req = "SELECT * FROM hotel WHERE num = " + num;
result = stmt.executeQuery(req);
}
//result.next();
int xxnum = result.getInt(1);
String nom = result.getString("nom");
String villeV = result.getString("ville");
int etoilesV = result.getInt("etoiles");
String directeur = result.getString("directeur");
Hotel hol = new Hotel(num, nom, villeV, etoilesV, directeur);
result.close();
stmt.close();
return hol;
} catch (SQLException ex) {
throw new DAOException("probl�me r�cup�ration de la liste des hotels !!", ex);
} finally {
closeConnection(conn);
}
The error
java.sql.SQLException: Invalid operation for the current cursor location.
will be caused by not setting the cursor to the next position using
result.next();
Place the call in an if statement
if (result.next()) {
// build Hotel object
...
}
If you still don't see any results, run your SQL directly against your database and see if any records are returned. If not, adjust your query or data accordingly.
Side Notes:
Use PreparedStatement to protect against SQL Injection attacks.
Place result.close(); and stmt.close(); calls in a finally block.
You need to use next() method of ResultSet.
Check the Javadocs here and I have snipped the relevant part below.
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
So you need to do this in your code:
if(result.next())
{
int xxnum = result.getInt(1);
String nom = result.getString("nom");
String villeV = result.getString("ville");
int etoilesV = result.getInt("etoiles");
String directeur = result.getString("directeur");
}

Categories