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();
Related
I have a code that reads from an SQL Database and saves each column of information into an ArrayList. I need to pass each ArrayList into a separate class where I can store the lists as single pieces of information (IE: Information in the first part of ArrayList1 goes with information in the first part of ArrayList2 etc...) and then sort them. I don't know how to pass that information to another class though. This is a section of my main method that stores the information into a list. I need this information passed to a separate class called List.java:
String SelectStatement1 = "SELECT InvoiceID FROM Invoice;";
ps = conn.prepareStatement(SelectStatement1);
rs = ps.executeQuery();
int count = 0;
while (rs.next()){
count++;
}
ps.close();
ps = conn.prepareStatement(SelectStatement1);
rs = ps.executeQuery();
ArrayList<String> InvoiceIDList = new ArrayList<String>();
String InvoiceID = null;
int p = 0;
while (p < count){
rs.next();
InvoiceID = rs.getString("InvoiceID");
InvoiceIDList.add(InvoiceID);
p++;
}
ps.close();
p = 0;
Edit: This is only a section of my code, I already have the code open and close the connections, I only need information on how to pass the ArrayList to another class for sorting.
Create a method in your other class like this:
public void receiveList (ArrayList<String> invoiceIDList) {
// Do something with invoiceIDList data
}
It may not be a bad idea to create a constructor in your "List" class, that accepts the ArrayList and creates the class instance with the required data
Also, please change the name of that class!! It will be confusing to others who read your code, as you are passing an ArrayList already!
EDIT:
You could also have your class implement the List interface, which would make things a lot easier for you, because you can insert data into your class based on the position of the data in the ArrayList.
public class yourClass implements List<String> {
// Your class methods and variables...
}
If you wanted to expand on this to allow more than just Strings, you can change to: List<T>, this would give you a more generic approach.
First, I suggest you perform a SELECT COUNT() instead of iterating your rows in your first query. Then remember to close() both the PreparedStatement and ResultSet. Finally, I would suggest you program to the List<String> interface. Putting it all together like,
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Connect to your database and initialize conn.
int count = 0;
try {
String query1 = "SELECT COUNT(InvoiceID) FROM Invoice;";
ps = conn.prepareStatement(query1);
rs = ps.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (Exception ignored) {
}
try {
ps.close();
} catch (Exception ignored) {
}
}
The above block of code is necessary to close() both rs and ps in the correct order with the finally Block.
List<String> invoiceIdList = new ArrayList<>();
try {
String query2 = "SELECT InvoiceID FROM Invoice;";
ps = conn.prepareStatement(query2);
rs = ps.executeQuery();
while (rs.next()) {
invoiceIdList.add(rs.getString("InvoiceID"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally { // <-- it's identical to the finally block above.
try {
rs.close();
} catch (Exception ignored) {
}
try {
ps.close();
} catch (Exception ignored) {
}
}
// now you can pass invoiceIdList elsewhere...
if (!invoiceIdList.isEmpty()) {
doSomething(invoiceIdList);
}
I know it is basics and probably really simple, but I'm struggling with the following situation where i want to query the database for a specific int(id in my case), but somehow i can't acces the returned data from the data set.
I have tested the query in db managment system and it works. I get no errors/ stacks but the result of my method is always -1.(Which means it fails :( because no int has been parsed)
code:
public int UserFactoryEngine(String n, String p){
// query for user data, validate and return
Connection conn = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
System.out.println("Failure intialization of the driver! ");
e.printStackTrace();
}
String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=BugsSurveillance;user=sa;password=1234;integratedSecurity=true;";
try {
conn = DriverManager.getConnection(connectionUrl);
} catch (SQLException e) {
System.out.println("Failure intialization of the connection! ");
e.printStackTrace();
}
System.out.println("Connected... ");
String sqlquery;
PreparedStatement preparedStatement;
ResultSet rs;
try {
preparedStatement = conn.prepareStatement("SELECT id FROM Users WHERE name = ? AND pass = ? ",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
preparedStatement.setString(1, n);
preparedStatement.setString(2, p);
rs = preparedStatement.executeQuery();
while (rs.next()){
System.out.println(rs.getInt(1));
}
} catch (SQLException e) {
System.out.println("Prepared statement failure!");
e.printStackTrace();
}
return -1;
}
You're not getting any output to the console from the
while (rs.next()){
System.out.println(rs.getInt(1));
}
because there are no results. Initially the ResultSet is pointed before the first row. When next() is called, it increments to the next row, and returns true only if the new current row is valid, which it must not be in this case.
Since you say the row exists, try replacing your lines
preparedStatement.setString(1, n);
preparedStatement.setString(2, p);
with hard coded values, for testing. So, if your username is admin, and your password is 1234.
preparedStatement.setString(1, "admin");
preparedStatement.setString(2, "1234");
Another test you could try is to
SELECT * FROM users
and see if you get any results that way.
Considering this is a login factory(what i'm trying to implement) i have been using a JPasswordField, which it seems needs a bit more atention when it comes to the getPassword() method. So because of that I wasen't able to succesfully find some matching string in database.
Fix: used JTextfield with hidden characters.
I am having many rows in table and I ran the same query on my database which is MySql but java ResultSet is only giving the first row of the table. Here is my code.
public ArrayList<String> getAllAlbumsName(Integer uid) {
ArrayList<String>allAlbumsName = new ArrayList<String>();
try {
String qstring = "SELECT albumname FROM picvik_picture_album WHERE " +
"uid = '" + uid + "';";
System.out.println(qstring);
connection = com.picvik.util.MySqlConnection.getInstance().getConnection();
ptmt = connection.prepareStatement(qstring);
resultSet = ptmt.executeQuery();
if(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
resultSet.close();
ptmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return allAlbumsName;
}
if(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
If you would like to get all rows, it should be:
while(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
The while statement continually executes a block of statements while a particular condition is true
Note: As #BalusC commented, your code would introduce SQL Injection attack, it is better to use ptmt.set... Instead of constructing SQL String manually.
try while(resultSet.next()) {
instead of if (resultSet.next()) {
Change if (resultSet.next()) { to while (resultSet.next()) {
Here's my static utility:
//String sqlQuery = "select count(name) as num from tbname where name = ?"
//String name = "testString";
private static int correct(Connection connection, String sqlQuery, String name) {
int result = 0;
PreparedStatement statatement = null;
ResultSet rs = null;
try {
statatement = connection.prepareStatement(sqlQuery);
statatement.setString(1, name);
rs = statatement.executeQuery();
while (rs.next()) {
result = rs.getInt("num");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
statatement.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
return result;
}
}
The method above returns 0 (incorrect result), but the following one returns '1' (it works OK, it the same sql query):
//String sqlQuery = "select count(name) as num from tbname where name = 'testString'"
private static int correct(Connection connection, String sqlQuery, String name) {
int result = 0;
PreparedStatement statatement = null;
ResultSet rs = null;
try {
statatement = connection.prepareStatement(sqlQuery);
rs = statatement.executeQuery();
while (rs.next()) {
result = rs.getInt("num");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
statatement.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
return result;
}
}
Could you please give me any advise, so I could resolve the problem.
PS: I'm not sure if it does matter, but the actual streetName - has a name in windows-1251 encoding (Russian) text.
PPS: The database is Oracle 10.
It might be a character set issue. According to the Oracle JDBC Drivers release 10.1.0.2.0 (10g) README:
The following is a list of known
problems/limitations:
If the database character set is AL32UTF8, you may see errors under the
following circumstances:
accessing LONG and VARCHAR2 datatypes.
binding data with setString() and setCharacterStream().
So if your database character set is AL32UTF8, you might have to get it changed to something else.
Also, what is the datatype of your column? VARCHAR2?
It seems the encoding conflict with the one which you set in your DB encoding charset and the the String you are passing..
You can do these 2 tries
Set the DB encoding to UTF-8 and then give a try. If this does not work you may go with following 2nd option
Set DB encoding charset to UTF-8 and also set the String by using this String constructor String(byte[] bytes, String charsetName)
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