Hello there, java/database near where syntax error - java

Everytime i try to update it says - near "WHERE":syntax error. I have successfully been able to update other parts of the classes in the program but this somehow gives me this error.
I think the problem lies here:
public void update_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="UPDATE tblUsers SET fullname='" + txtFullname.getText()+"',"
+ "username='" + txtUsername.getText()+"',"
+ "password='" + txtPassword.getText()+"',"
+ "WHERE userID="+ accid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Reference successfully updated!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
Here's the whole code just in case;
public void update_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="UPDATE tblUsers SET fullname='" + txtFullname.getText()+"',"
+ "username='" + txtUsername.getText()+"',"
+ "password='" + txtPassword.getText()+"',"
+ "WHERE userID="+ accid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Reference successfully updated!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()

For sql table update, the syntax is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Notice that there is no comma before the where keyword. In your code, you are adding the comma before your WHERE keyword leading to the error

Related

Getting error "statement.executeupdate() cannot issue statements that produce result sets." when trying to insert into mysql using JDBC

I'm trying to get the primary auto incremented key from one table and store this in another using MySQL connector and JDBC. Although its giving me this error:
statement.executeupdate() cannot issue statements that produce result
sets.
I think its something to do with the storing of the integer variable but not too sure.
public void insertIntoWorkoutLogs(String field_setNumber, String field_repNumber, String field_weightAmount) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
String insert ="INSERT INTO `workout`.`workoutlogs`" + " (`SetNumber`, `RepNumber` , `WeightAmount`)"
+ "VALUES('" +field_setNumber+"','"+field_repNumber+"','"+field_weightAmount+"')";
statement.executeUpdate(insert);
int workoutID = insertQueryGetId("SELECT workoutID FROM workout");
String insert2 ="INSERT INTO `workout`.`workoutlogs`" + " (`WorkoutID`)"
+ "VALUES('" +workoutID+"')";
statement.executeUpdate(insert2);
connection.close();
}catch(Exception e) {
System.out.println(e);
}
}
public int insertQueryGetId(String query) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
int workoutID=0;
int result=-1;
try {
workoutID = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs.next()){
result=rs.getInt(1);
}
rs.close();
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
I've tried using statement for this, but I'm thinking it may have to be prepared statement for it to work. Expecting to store the auto incremented primary key of one table (workouts) into a field within another table (workoutlogs).
It's because you are passing wrong query. Statement.RETURN_GENERATED_KEYS works with Insert queries not with Select queries.
When you insert a row in database, an auto increment value gets generated and is returned but you are passing a Select statement
As Syed Asad Manzoor said, it will work for you but then you need to remove Statement.RETURN_GENERATED_KEYS and statement.executeQuery() has return type of ResultSet so you need to store the result in ResultSet only.
public void insertIntoWorkoutLogs(String field_setNumber, String field_repNumber, String field_weightAmount) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
String insert ="INSERT INTO `workout`.`workoutlogs`" + " (`SetNumber`, `RepNumber` , `WeightAmount`)"
+ "VALUES('" +field_setNumber+"','"+field_repNumber+"','"+field_weightAmount+"')";
statement.executeUpdate(insert);
**int workoutID = insertQueryGetId("SELECT workoutID FROM workout");** // Line of Concern 1
String insert2 ="INSERT INTO `workout`.`workoutlogs`" + " (`WorkoutID`)"
+ "VALUES('" +workoutID+"')";
statement.executeUpdate(insert2);
connection.close();
}catch(Exception e) {
System.out.println(e);
}
}
public int insertQueryGetId(String query) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
int workoutID=0;
int result=-1;
try {
// Line of Concern 2
**workoutID = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);**
In line (marked as Line of Concern 1 ..
int workoutID = insertQueryGetId("SELECT workoutID FROM workout"); you are passing query as "SELECT...." and at point marked as Line of Concern 2
workoutID = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); you are using executeUpdate.. thats why exception is thrown.
Change statement.executeUpdate(query) to statement.executeQuery(query)..
The INSERT statement needs to have flag RETURN_GENERATED_KEYS.
Then getting the ResultSet would deliver for every insert record the generated key(s).
Also use a PreparedStatement for escaping of strings and against SQL injection.
Use try-with-resources to automatically close the several objects, even with exception or early return.
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/workout", "root", "")) {
String insertSql = "INSERT INTO `workout`.`workoutlogs`"
+ " (`SetNumber`, `RepNumber` , `WeightAmount`)"
+ " VALUES(?, ?, ?)";
try (PreparedStatement statement = connection.prepareStatement(insertSql,
Statement.RETURN_GENERATED_KEYS)) {
statement.setString(field_setNumber);
statement.setString(field_repNumber);
statement.setBigDecimal(field_weightAmount);
statement.executeUpdate();
try (ResultSet rs = statement.getGeneratedKey()) {
if (rs.next()) {
int workoutID = rs.getInt(0);
//... second insert here
}
}
}
}

Can't figure out how to get rid of syntax error on mysql

I'm trying to run a statement on the java main file and I'm able to connect to the data base, but not run the sql statement
my code is:
try {
System.out.println("Connecting to the database...");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Connected to database successfully");
System.out.println("Inserting");
stmt=conn.createStatement();
String sql="USE TheEmployeeDatabase" +
"SELECT * FROM EmployeeTable";
stmt.executeUpdate(sql);
System.out.println("worked");
} catch (SQLException e) {
e.printStackTrace();
}
and getting the error
You have an error in your SQL syntax
As long as the schema name TheEmployeeDatabase1 is part of your DB_URL, you don't need to have the USE TheEmployeeDatabase statement.
You statement should just be:
SELECT * FROM EmployeeTable
String sql="USE TheEmployeeDatabase " <--- you need whitespace here or you will have TheEmployeeDatabaseSELECT concatenated

How to Properly use Select Max() in Eclipse

I am working on a school project where I must interact with an access database. I'm attempting to
SELECT Max(GameID) AS MaxID
FROM Games
However, This query when ran through the Eclipse application I built only returns in the console
SQL Exception: UCAExc:::4.0.3 Column not found: GameID
SQL State: S1000
Vendor Error: -421
I have checked the access database and the column DEFINITELY EXISTS. I ran the query in the access database and it worked in there as well. I'm not sure what I'm missing or if this is possible. How can i grab the highest value of gameID's?
here is the connection to the database
ResultSet rs = null; //will hold record that get returned
Statement stmt = null; //will hold the SQL statement we want to run
try
{
//2. Establish the connection
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://C:/Users/Public/ZaccaroBlottoDB.accdb");
//3. Create the statement
stmt = conn.createStatement();
String theQuery = "SELECT Max("
+ "GameID)"
+ " As MaxID"
+ " FROM Games"
+ " WHERE (1=1)";
//4. Execute the statement
rs = stmt.executeQuery(theQuery);
//5. Process the results
while (rs.next())
{
int gameID = rs.getInt("GameID"); //note the type and the field name from the DB
System.out.println(gameID);
//addGameIDFTF.setText(Integer.toString(gameID +1));
}//while
//6. Close the Connection
rs.close();
conn.close();
}
catch (SQLException ex)
{
System.out.println("SQL Exception: " + ex.getMessage());
System.out.println("SQL State: " + ex.getSQLState());
System.out.println("Vendor Error: " + ex.getErrorCode());
ex.printStackTrace();
} //catch
I think the issue is the value that you are retrieving. As you have mentioned the alias name to be MaxID you should get MaxID from result_set instead of GameID
Hence, It should be
int gameID = rs.getInt("MaxID");
instead of
int gameID = rs.getInt("GameID");

Delete from SQLite Database

I have an SQLite database linked up to my Java project within Eclipse. I'm able to delete entries from the database when I give a hardcoded, specified ID such as '3'. I'm trying to alter the code in order to enable the user the manually pass any number and have it delete that entry.
public static String deleteRecords(String NumberDelete){
Connection dbConnection = null;
Statement statement = null;
try{
dbConnection = getDBConnection();
dbConnection.setAutoCommit(false);
statement = dbConnection.createStatement();
String sql = "DELETE from employees where ID='NumberDelete';";
statement.executeUpdate(sql);
dbConnection.commit();
statement.close();
dbConnection.close();
} catch(Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return NumberDelete;
}
You need to use PreparedStatement to pass the parameters to query and execute it, the method will look like this:
public static String deleteRecords(String NumberDelete) {
Connection dbConnection = null;
PreparedStatement statement = null;
String sql = "DELETE from employees where ID= ? ;";
try {
dbConnection = getDBConnection();
dbConnection.setAutoCommit(false);
statement = dbConnection.prepareStatement(sql);
statement.setString(1, NumberDelete);
statement.executeUpdate(sql);
dbConnection.commit();
statement.close();
dbConnection.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return NumberDelete;
}
This will set the number in the query and execute it. If the number is of type int then you need to use setInt to set the value. Here is the javadoc for PreparedStatement.
For user input, you might want to check out the Scanner class: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Once you get an integer from the user, parse it, and store it in a variable, you can simply use String concatenation:
String sql = "DELETE from employees where ID='" + userInput + "';";

Inserting email in SQLite database using JDBC

I am trying to insert an email ID to a table in my SQLite3 Database. In my case it successfully creates the table but gives an error while inserting a record in it - "near "#gmail": syntax error". How can i resolve this ? Here is the code -
public void insertData(String emailId, double gtse, long receivedDate) throws ClassNotFoundException, SQLException{
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:testdb.sqlite");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
ResultSet result = statement.executeQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='T1'");
if(!result.next()){
statement.executeUpdate("create table T1 (email TEXT, gtse REAL, receiveddate DATE)");
statement.executeUpdate("insert into T1 values(" + emailId + ", "+ gtse +", "+ receivedDate +")");
}
else{
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
Your core error is that for the insert query you are not enclosing the values to be inserted, in quotes. Your query, after construction, looks something like this:
insert into T1 values(whatever#gmail.com, emailtexthere, 04-07-2013)
When it should be something like this:
insert into T1 values('whatever#gmail.com', 'emailtexthere', '04-07-2013')
The SQL parser chokes while trying to parse your current query, because the syntax is incorrect. The solution to this problem is not simply to enclose the values in quotes though, but rather to use prepared statements. This is because the way you are constructing your query right now is vulnerable to SQL injection attacks. Here is an example of using a prepared statement:
PreparedStatement pStmt = conn.prepareStatement(
"INSERT INTO T1 VALUES(?, ?, ?)");
pStmt.setString(1, emailId);
pStmt.setString(2, gtse);
pStmt.setDate(3, receivedDate);
pStmt.execute();

Categories