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.
Related
So currently Im trying to do get the auto-incremented primary key by following this answer
Primary key from inserted row jdbc? but apparently the program can't even reach that line and the error appeared on the ps.executeQuery() line after debugging the program, the error it display was only "executeQuery" is not a known variable in the current context. that line, which didn't make sense to me. So how do I go pass this hurdle?
public static int createNewLoginUsers(String newPassword, String newRole) throws SQLException{
Connection conn = DBConnection.getConnection();
Statement st = null;
ResultSet rs = null;
PreparedStatement ps = null;
int id = 0;
try{
String sql = "INSERT into Login(password, role) VALUES(?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, newPassword);
ps.setString(2, newRole);
ps.executeUpdate();
st = conn.createStatement();
rs = st.executeQuery("SELECT * from Login");
rs.last();
System.out.println(rs.getInt("username"));
id = rs.getInt("username");
rs.close();
} finally{
try{
conn.close();
}catch(SQLException e){
System.out.println(e);
}
}
return id;
}
The part of the method which calls the createNewLoginUsers method
if(newPasstxtfld.getText().equals(retypeNewPasstxtfld.getText())){
//update into database
try {
int username = CreateUsersDAO.createNewLoginUsers( (String) newUserRoleBox.getSelectionModel().getSelectedItem(), newPasstxtfld.getText());
Alert confirmation = new Alert(Alert.AlertType.INFORMATION);
confirmation.setHeaderText("New User Details has been created. Your username is " + username);
confirmation.showAndWait();
} catch (SQLException e) {
}
EDIT:
Databases table added and it's in the provided link below
https://imgur.com/a/Dggp2kc and edit to the codes instead of 2 try blocks in one method i have placed it into a different similar method, updated my codes to the current one I have.
Basically I am trying to find how many people in mysql database are registered by a specific name using SELECT command with my java program. The command executes without any error but the result is something different than I have in my db.
Here is my java code I am using to get UIDs:
public void usernameAvail_fun(){
String query = "SELECT UID FROM db.tb WHERE UFN=\"myuid\"";
ResultSet ursa;
try {
ursa = st.executeQuery(query);
System.out.println(ursa.toString());
} catch (SQLException e) {
e.printStackTrace();
}
}
and i happen to get the result as: com.mysql.jdbc.JDBC42ResultSet#11719758
You are printing a java object so output is there. If you want to print uid use following statement -
while (ursa.next()){
System.out.println(ursa.getString(1));
}
Initialize ursa to null first.
adding a PreparedStatement
public void usernameAvail_fun(){
String query = "SELECT UID FROM db.tb WHERE UFN=\"myuid\"";
ResultSet ursa= null;
try {
PreparedStatement stmt = con.prepareStatement(query);
ursa= stmt.executeQuery();
while(ursa.next()) //print
{
ursa.getString(1); //or ursa.getString("//your column name");
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
I'm want to delete a person from the database "person" on a given id. It works if I don't use Prepared Statement (the first 5 unmarked lines of code in the try-statement).
But when I try to do it using Prepared Statement it does not work, and I canĀ“t figure out why?
The application gets stuck on prepStatement.executeUpdate();
Therefore I can't even see the value of executeUpdate (if I want to se how many Changes that are made).
I have a similar method, addPerson, where Prepered Statement works perfect. This really confuses me...
I appreciate your help.
private void removePerson() {
int id = Integer.parseInt(idField.getText());
PreparedStatement prepStatement = null;
try {
*/* Statement statement = connection.createStatement();
String sql = "DELETE FROM person WHERE id = '"+id+"'";
statement.executeUpdate(sql);
System.out.println("Person removed from database...");
ResultSet result = statement.executeQuery(sql);
*/*
String sql = "DELETE FROM person WHREE id = ?";
prepStatement = connection.prepareStatement(sql);
prepStatement.setInt(1, id);
prepStatement.executeUpdate();
System.out.println("Person removed from database...");
}
catch (SQLException se) {
se.toString();
}
finally {
try {
prepStatement.close();
}
catch (SQLException ex) {
ex.toString();
}
}
}
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();
I am trying to create a simple web app that saves user data from a form to a database and reads the content of the database back to browser upon request. Following are the functions I have written so far.
connectToDB() // connects to database
addEmployee() // adds employee to database
displayEmployee() // returns a resultSet
isExisted(int staffID) // checks if the staff already exists
Database connection function:
public void connectToDB(){
try{
// load Apache derby driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
} catch(ClassNotFoundException e) {
System.err.println(e);
}
try{
connection = DriverManager.getConnection(DBNAME, USERNAME, PASSWORD);
} catch(SQLException e){
System.err.println(e);
}
} // end connectToDB
Display Employee function:
public ResultSet displayEmployee(){
connectToDB();
ResultSet result = null;
try{
Statement stmt = connection.createStatement();
String query = "SELECT * FROM APP.ADDRESSBOOK";
result = stmt.executeQuery(query);
} catch(SQLException e) {
System.err.println(e);
}
return result;
}
Check if employee exists:
public boolean isExisted(int StaffID){
connectToDB();
try{
Statement stmt = connection.createStatement();
String query = "SELECT StaffNum FROM APP.ADDRESSBOOK WHERE StaffNum = " + staff_number;
ResultSet result = stmt.executeQuery(query);
while(result.next()){
int temp = result.getInt(1);
if(temp == staff_number){return true;}
}
} catch(SQLException e) {
System.err.println(e);
}
return false;
}
As you can see, if you compare the displayEmployee() and isExisted(), I am repeating mysel. Both the function works but I am looking to refactor the code. In those function I havent closed the connection. If there were 20 functions in the web app that connects to the database my code would stink.
I am looking something like this:
* THIS CODE DOESNT WORK ******
private Statement queryDB(query){
connectToDB();
Statement stmt;
try{
stmt = connection.createStatement();
} catch(SQLException e) {
System.err.println(e);
}
return stmt;
// code for closing connection
}
public ResultSet DisplayEmployee(){
String query = "SELECT * FROM APP.ADDRESSBOOK";
Statement stmt = queryDB(query);
ResultSet result = stmt.executeQuery(query);
return result;
}
Thanks.
Using raw JDBC produces a lot of unsightly boilerplate code. One solution is to use Spring JDBC Template.
In addition you will get the sql exception hierarchy which will manage the underlying JDBC exceptions automatically as runtime exceptions.
For more see:
Introduction to Spring Framework JDBC
A couple of comments:
The catch statement of ClassNotFoundException should throw an exception and shouldn't continue further.
It is not a good idea to return resultsets from a method that obtained them upon statement execution, since it is the responsibility of that method to close it. Instead, you should either read out the results into objects or cache them into CachedRowSet if your downstream functions expect a resultset.
The connectToDB method should return a successful connection or throw exception.
You could write a method that takes in an SQL query and return the results as objects so that this method can be used for retrieving based on different criteria as long you are retrieving the objects of same type.
isExisted is using staff_number which I think you intend it to be staffID. If you found a row with this value, then there is no need to check if the result set contained the row with this value, right?
My two cents!