java try with resources : empty result set - java

I am trying to update a user in my db with a java try-with-resources statement. I however get an error message returned that my resultset is empty. Having read various other posts, they suggest to use ps.executeUpdate() instead of ps.executeQuery(), but this returns an int which (stating the glaringly obvious) does not have the type "Auto closable", which means the code does not even pass compile.
Does anyone have an example of how to bypass this?
public void updateUser (String id, String value){
try (Connection con = DriverManager.getConnection("jdbc:databasetype://localhost:5432/database");
PreparedStatement ps = createUpdateStatement(con, id, value);
ResultSet rs = ps.executeQuery())
{
System.out.println("Add operation completed");
} catch(Exception e) {
System.out.println("Exception: " + e.getMessage() + " Thrown by: " + e.getClass().getSimpleName());
}
}

You only need resources within the try if they implement Closeable. As you said, a primitive integer cannot so move it out of the try-with-resources and into the body:
public void updateUser (String id, String value)
{
try (Connection con = DriverManager.getConnection("jdbc:databasetype://localhost:5432/database");
PreparedStatement ps = createUpdateStatement(con, id, value))
{
int result = ps.executeUpdate();
System.out.println("Add operation completed");
} catch(Exception e) {
System.out.println("Exception: " + e.getMessage() + " Thrown by: " + e.getClass().getSimpleName());
}
}

Move the ps.executeUpdate into the body of the try:
try (Connection con = DriverManager.getConnection("jdbc:databasetype://localhost:5432/database");
PreparedStatement ps = createUpdateStatement(con, id, value)) {
ps.executeUpdate();
System.out.println("Add operation completed");
} catch(Exception e) {
System.out.println("Exception: " + e.getMessage() + " Thrown by: " + e.getClass().getSimpleName());
}

Related

MySQL checking if a entry is set

Im trying to check if a entry is set, so for example in a row with: user, password, birth
I check if in column user f.e. "mxrlin" is
For that im using that code in my Main Class:
if(!mySQL.isSet(tableName, "houseNumber", houseNumberStr)){
System.out.println(house.getHouseNumber() + " not set yet");
inserts.add(new BetterMySQL.KeyValue("houseNumber", houseNumberStr));
mySQL.insertEntry(tableName, inserts);
}else {
System.out.println(house.getHouseNumber() + " set -> updating");
mySQL.update(tableName, inserts, "houseNumber", houseNumberStr);
}
And the mySQL.isSet() method looks like this:
public boolean isSet(String tableName, String key, String value){
Check.checkNotEmpty(tableName);
Check.checkNotEmpty(key);
Check.checkNotEmpty(value);
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE ?=?", Arrays.asList(key, value));
try {
if(resultSet.next()){
return resultSet.getObject(value) != null;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
But with this code it always debugs me "house.getHouseNumber() + " not set yet", so the Class doesnt find the entry that is set
You can't bind a parameter to a column name. The key in this case will be treated as a string literal in SQL.
Assuming a method call like this:
mySQL.isSet("houses", "houseNumber", "2335")
this code:
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE ?=?", Arrays.asList(key, value));
Will generate a SQL statement equivalent to
SELECT * FROM houses WHERE 'houseNumber'='2335'
Of course, the string 'houseNumber' will never equal the string '2335', so no results will be returned.
You'll need to substitute key into the SQL string, just like tableName already is:
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE " + key + "=?", Arrays.asList(value));

MySQLSyntaxErrorException while trying to update database

I'm doing an app for school project and I came across this error I've tried to figure it out but I can't seem to fix it.
Let me explain the problem first, basically I'm trying to update previously created user. Initially the profile has only username and a password. I want the user to be able to add whatever details he wishes to later on once he has created his own profile.
I have one class which has the database connectivity and update Profile method. The other class is a jFrame where user can input some data into textfields and the intention is that it will be inserted into fields for existing profile within the database (Initially those fields are declared as null).
Below you can see my DBConnect class which contain the Login method and UpdateProfile method. In the login method I'm creating a profile object which holds all the variables and methods such as getUsername, getPassword etc.
public class DBConnect {
private Connection dbConnection;
public Profile profile;
public DBConnect() {
try {
dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/prototype?user=root");
} catch (Exception ex) {
System.out.println("Connection failed :" + ex);
}
}
public void Login() {
profile = new Profile(LoginWindow.usernameField.getText(), LoginWindow.passwordField.getText());
Statement userQuery = null;
try {
//Look for the user with valid username and password
userQuery = dbConnection.createStatement();
ResultSet rs = userQuery.executeQuery("Select * FROM Profile WHERE pName = \"" + profile.getUsername() + "\" and password = \"" + profile.getPassword() + "\"");
if (rs.next()) {
profile.isLoggedin(true);
} else {
profile.isLoggedin(false);
}
} catch (SQLException ex) {
profile.isLoggedin(false);
System.out.println(ex);
} finally {
try {
if (userQuery != null) {
userQuery.close();
}
} catch (SQLException ex) {
System.out.println("Failed to close login query");
}
}
}
public void updateProfile(String _height, String _weight, String _goalWeight, String _age) {
Statement updateQuery = null;
try {
updateQuery = dbConnection.createStatement();
updateQuery.executeUpdate("UPDATE Profile SET height='" + _height + "',weight='" + _weight + "',goalWeight='" + _goalWeight + "',age='" + _age + "' WHERE pName =" + profile.getUsername());
} catch (SQLException ex) {
System.out.println(ex);
} finally {
try {
if (updateQuery != null) {
updateQuery.close();
}
} catch (SQLException ex) {
System.out.println("Failed to close updateCustomer query");
}
}
}
}
I'm trying to update some of the fields that were empty with the Update Profile method and to get the profile that I want to update I wrote "WHERE pName =" + profile.getUsername());" in order to retrieve the record of the user.
Finally in the EditProfile jFrame I wrote this method to pass on the parameters for the updateProfile methods.
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {
LoginWindow.dbc.updateProfile(heightTextField.getText(), weightTextField.getText(), goalWeightTextField.getText(), ageTextField.getText());
}
Everything compiles but I'm having mySQLSyntaxError which is:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'Admin' in 'where clause'
The database is not updated and I don't know how to fix it.
My assumptions is that there is a problem with "WHERE pName =" + profile.getUsername());" in updateProfile declaration. The "Admin" is the result of profile.getUsername(); and its the actual username of currently logged in user.
Please help.
You have a little syntax error: Your line
updateQuery.executeUpdate("UPDATE Profile SET height='" + _height + "',weight='" + _weight + "',goalWeight='" + _goalWeight + "',age='" + _age + "' WHERE pName =" + profile.getUsername());
should read
updateQuery.executeUpdate("UPDATE Profile SET height='" + _height + "',weight='" + _weight + "',goalWeight='" + _goalWeight + "',age='" + _age + "' WHERE pName ='" + profile.getUsername()) + "'";
(You need to enclose the pName parameter with single quotes.)
...and you really need to start using PreparedStatement as others also suggested.
that exactly the problem. try that:
ResultSet rs = userQuery.executeQuery("Select * FROM Profile WHERE pName = '" + profile.getUsername() + "' and password = '" + profile.getPassword() + "' ");

Java connection to database

I have exhausted all avenues to sort out this problem, but to no avail. I have installed "SQL Management Studio 2012" and created a dummy database and methods, but I'm still getting a "null point exception pointer". Java and JDBC is set under user variables.
Here are the screen shots and code.
Static {
// standard code to open a connection and statement to SQL Server database
try {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://SQL-SERVER;"
+ "databaseName=ItunesDB;integratedSecurity=true;";
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
} // Handle any errors that may have occurred.
catch (SQLException sqle) {
System.out.println("Sql Exception :" + sqle.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found Exception :" + e.getMessage());
}
}
public static String listAll() {
String output = "";
try {
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable");
while (res.next()) { // there is a result
// the name field is the thrid one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
output += res.getString(1) + " " + res.getString(2) + " - "
+ res.getString(3) + " " + res.getString(4) + " "
+ res.getString(5) + "\n";
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return output;
}
public static String getName(String key) {
try {
SELECT * FROM LibraryTable WHERE key = '04'
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable WHERE ID = '" + key + "'");
if (res.next()) { // there is a result
// the name field is the second one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
return res.getString(2);
} else {
return null;
}
} catch (Exception e) {
System.out.println(e);
return null;
}`enter code here`
The database information:
Dummy Database
ID Name Artist Quantity Price Rating Playcount
What do I need to do to fix this?
Re install sql server in mixed mode . Then go to SQL Server configuration manager and checks is the TCP/Ip is enable . IF not enable it and restart the service. Then add sqljdbc jar in your project . Then try this code
Connection con = null;
try {
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;"
+ "user=sa;password=HerongYang;"
+ "database=AdventureWorksLT");
}
user is always sa because it is the system administrator

Connection from Java Application and Stored Procedure MSSQL

I have the stored procedure in SQL Sever and it has a few parameter. I would like to give the value of parameter from the combo box (in java application). I've read this code (look at below)
public static void executeSprocInParams(Connection con) {
try {
PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}");
pstmt.setInt(1, 50);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("EMPLOYEE:");
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
System.out.println("MANAGER:");
System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("ManagerFirstName"));
System.out.println();
}
rs.close();
pstmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
But i didn't get the meaning. Is there any tutorial that give me some example just like in my case? Thanks for any reply
PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}");
pstmt.setInt(1, 50);
ResultSet rs = pstmt.executeQuery();
1) Line 1 creates a prepare statement object with your Stored Procedure. The ? is the placeholder for the input parameter to the Stored Procs
2) Line 2 sets the input param to the stored proc
3) executeQuery executes the stored proc by providing the input and get the output as a resultset.
while (rs.next()) {
System.out.println("EMPLOYEE:");
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
System.out.println("MANAGER:");
System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("ManagerFirstName"));
System.out.println();
}
rs.close();
pstmt.close();
Above lines iterate over the result set and print each record
public static void executeSprocInParams(Connection con) {
try {
PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}");//Creating a prepared statement with the string to execute your procedure.
pstmt.setInt(1, 50);//This is to set the parameter to the place holder '?'
ResultSet rs = pstmt.executeQuery();//This is to execute your procedure and put the result into a table like set
while (rs.next()) {//To check if there are any values in the set, if so the print those values
System.out.println("EMPLOYEE:");
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
System.out.println("MANAGER:");
System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("ManagerFirstName"));
System.out.println();
}
rs.close();//close the set
pstmt.close();//close the statement
}
catch (Exception e) {
e.printStackTrace();
}
}

Suddenly getting SQL Exceptions when using sql variables in statements

I have a SQL query, consisting of different statements (this is a simplified version, which also triggers the error) :
private static String getActiveKeyEventsSql =
"SET #report_model_id = 2; " +
"SELECT MAX(report_ts) AS report_ts " +
"FROM `pulse_data`.`key_event_reports` " +
"WHERE report_model_id = #report_model_id ";
I am trying to call that statement from inside my Java Application:
public static void main(String[] args) throws Exception {
MySQLLayer _db = new MySQLLayer();
Connection _conn = null;
try {
_conn = _db.getConnection();
PreparedStatement getActiveKeyEventsStmt = _conn.prepareStatement(getActiveKeyEventsSql);
ResultSet rs = getActiveKeyEventsStmt.executeQuery();
while (rs.next()) {
LOG.info(rs.getLong("report_ts"));
}
} catch (SQLException e) {
LOG.error("COULD NOT GET MAX REPORT.", e);
} finally {
try {
if (_conn != null && !_conn.isClosed()) {
_conn.close();
}
} catch (SQLException e) {
LOG.info("COULD NOT CLOSE CONNECTION.", e);
}
}
}
But it triggers the following error:
java.sql.SQLException: ResultSet is from UPDATE. No Data.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6870)
at com.stockpulse.stockstorm.sentiment.JavaTest.main(JavaTest.java:36)
In other places of my application, this schema works just fine. When I copy this statement to the MySQL console, it works just fine.
Here is the String to init the DB:
config.setJdbcUrl(
"jdbc:mysql://" + cred.getHOST() + "/" + cred.getDB()
+ "?allowMultiQueries=true&characterEncoding=utf-8&useUnicode=true&rewriteBatchedStatements=true&relaxAutoCommit=true"
);
Why is JDBC behaving this way out of the sudden?
Try breaking your statement into
a = "SET #report_model_id = 2; ";
b = "SELECT MAX(report_ts) AS report_ts " +
"FROM `pulse_data`.`key_event_reports` " +
"WHERE report_model_id = #report_model_id ";
And do PreparedStatement.addBatch() for each.

Categories