My query is giving following error,Unexpected token WHERE - java

i'm working in java with sql.when ever this query is executed it gives me the error mentioned in title
try(PreparedStatement statement = conn.prepareStatement("INSERT INTO student_signup(q" + strId + ")" + "WHERE student_email="+email+"VALUES(?)")) {
statement.setString(1, SelectedOption);
statement.executeUpdate();
statement.close();
for a little code background
here
int questionID=1;
String strId = Integer.toString(questionID);
String email = signInForm.getTxtEmail().getText();

INSERT inserts new rows. I think you want to change a value in an existing row. For that, use UPDATE. Something like this:
UPDATE student_signup
SET strID = ?
WHERE student_email = ?;

INSERT is never use with WHERE clause
If you want to change the value for a pre-existing record in the database, you should try the UPDATE clause with WHERE condition after it.

Related

Insert new Value in MySQL in same Cloumn (Java/Code)

I am working on a little project.
Now I don't know, how to "replace" a old value in the mysql table.
Here you can see the table:
Thats my methods:
MySQL.update("INSERT INTO OnlineServer (Name) VALUES ('" + API.getServerFreeServer() + "');");
public static void update(String qry) {
try {
java.sql.Statement st = con.createStatement();
st.executeUpdate(qry);
st.close();
} catch (SQLException e) {
connect();
e.printStackTrace();
}
}
The problem now is, if I update the mysql, it dont replace the value in the column "Name". It just add a new Value under the old Value. The table is Going to be too huge if I Update every 5 seconds.
I need exactly one value in the column "Name".
So I have tryed to replace the insert but it doesn't work for me.
Maybe you have some ideas?
Sorry for my bad English, I'am German.
It sounds like you want to do an update here of the table, rather than an insert:
String sql = "UPDATE OnlineServer Set Name = ?";
PreparedStatement ps = dbConnection.prepareStatement(sql);
ps.setString(1, API.getServerFreeServer());
ps.executeUpdate();
By the way, your current query is doing raw string concatenation, making it prone to typos as well as SQL injection. I have used a prepared statement above, which is the most desirable way to execute a query using JDBC.
INSERT operation is for adding new record only and thus irrespective of you specify single column or 1million column it will add a new record. You actually need an UPDATE statement saying
UPDTE OnlineServer SET Name = <value>
You might also want to check INSERT ... ON DUPLICATE KEY UPDATE

How to get all the rows affected by a UPDATE query in JDBC?

I have an assignment where I need to update records using a PreparedStatement. Once the record have been updated as we know update query return count, i.e., number of row affected.
However, instead of the count I want the rows that were affected by update query in response, or at least a list of id values for the rows that were affected.
This my update query.
UPDATE User_Information uInfo SET address = uInfo.contact_number || uInfo.address where uInfo.user_id between ? AND ?;
Normally it will return count of row affected but in my case query should return the ids of row or all the row affected.
I have used the returning function of PostgreSQL it is working but is not useful for me in that case.
i have used returning function of PostgreSQL but is not useful for me
It should be. Perhaps you were just using it wrong. This code works for me:
sql = "UPDATE table1 SET customer = customer || 'X' WHERE customer LIKE 'ba%' RETURNING id";
try (PreparedStatement s = conn.prepareStatement(sql)) {
s.execute(); // perform the UPDATE
try (ResultSet rs = s.getResultSet()) {
// loop through rows from the RETURNING clause
while (rs.next()) {
System.out.println(rs.getInt("id")); // print the "id" value of the updated row
}
}
}
The documentation indicates that we can also use RETURNING * if we want the ResultSet to include the entire updated row.
Update:
As #CraigRinger suggests in his comment, the PostgreSQL JDBC driver does actually support .getGeneratedKeys() for UPDATE statements too, so this code worked for me as well:
sql = "UPDATE table1 SET customer = customer || 'X' WHERE customer LIKE 'ba%'";
try (PreparedStatement s = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
s.execute(); // perform the UPDATE
try (ResultSet rs = s.getGeneratedKeys()) {
while (rs.next()) {
System.out.println(rs.getInt(1)); // print the "id" value of the updated row
}
}
}
Thanks, Craig!
You might be able to use JDBC's support for getting generated keys. See the Connection.prepareStatement(String sql, int[] columnIndexes) API method, then use Statement.getGeneratedKeys() to access the results.
The spec says "the driver will ignore the array if the SQL statement is not an INSERT statement" but I think PostgreSQL's JDBC driver will actually honour your request with other statement types too.
e.g.
PreparedStatement s = conn.prepareStatement(sql, new String[] {'id'})
s.executeUpdate();
ResultSet rs = s.getGeneratedKeys();
Otherwise, use RETURNING, as Gord Thompson describes.
There are two way of doing it
1. by passing an array of column name or index of column prepareStatement
i.e conn.prepareStatement(sql, new String[] {'id','uname'})
and
2. by using Statement.RETURN_GENERATED_KEYS in prepareStatement.
My code is for this i.e as per my requirement i have developed my code you can have a look for better idea.
private static final String UPDATE_USER_QUERY= "UPDATE User_Information uInfo SET address = uInfo.contact_number || uInfo.address where uInfo.user_id between ? AND ?;";
//pst = connection.prepareStatement(UPDATE_USER_QUERY,columnNames);
pst = connection.prepareStatement(UPDATE_USER_QUERY,Statement.RETURN_GENERATED_KEYS);
ResultSet rst = pst.getGeneratedKeys();
List<UserInformation> userInformationList = new ArrayList<UserInformation>();
UserInformation userInformation;
while (rst.next()){
userInformation = new UserInformation();
userInformation.setUserId(rst.getLong("user_id"));
userInformation.setUserName(rst.getString("user_name"));
userInformation.setUserLName(rst.getString("user_lName"));
userInformation.setAddress(rst.getString("address"));
userInformation.setContactNumber(rst.getLong("contact_number"));
userInformationList.add(userInformation);
}
That think i need to achieve in this case.
Hope so this will help you a lot.

Postgresql with java: query produced no result after insert

I write a little program to admin my video collection.
/*
insert new data set into the table
*/
int next = 0;
rs = st.executeQuery("Select max(category_id) from category;");
if (rs.next()) {
next = rs.getInt(1) + 1;
System.out.println(next);
}
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
rs = st.executeQuery(query);
//on this place is the exception thrown
// this will not execute anymore
rs = st.executeQuery("DELETE FROM category WHERE name = 'Mystics';");
The program can select on tables, make joins but insert make trouble.
I try to insert some new data in my table (see Java-code). After the second test the output show me that the data was inserted. But after Insert was an exception thrown.
1 & 2 are the tests from yesterday and today. (3) was inserted but not selected yet.
1 Mystics 2015-07-05
2 Mystics 2015-07-06
3
org.postgresql.util.PSQLException: query produced no result.
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:287)
at postgre_java.Zetcode.main(Zetcode.java:55)
do you have some advises for me?
Do not manipulate data with read statements!
If you want to insert, update, delete data in db use
Statement stmt = conn.createStatement();
stmt.executeUpdate(SQL);
executeQuery returns resultset, but all that INSERT, UPDATE, DELETE can return is number of affected rows and that is what executeUpdate is returning.
And never, never, never*100 use string concatenation in SQL use Prepared statements!
In Java, you use executeQuery for a SELECT statement or some other statement which returns something. If you want to execute an INSERT, UPDATE or DELETE without returning something, you should use executeUpdate().
Statement#executeUpdate() is meant for that purpose
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
int noOfRows= st.executeQuery(query)
but it doesnt return a ResultSet , rather the no of rows affected that you could store into an Integer
Also your is highly vulnerable to Sql injection , try using the PreparedStatements to safeguard your code

Writing multiple where clauses in Java using Mysql

below is code is a code i wrote to get the value of 'monthly Depreciation' when i select the row on my j Table by either mouse-clicked or key-pressed. but it only selects the first value for 'monthly depreciation' when i click on the rows or key-press.the problem i know is coming from the where statement but can't seem to get around it.
if(evt.getKeyCode()==KeyEvent.VK_DOWN || evt.getKeyCode()==KeyEvent.VK_UP)
{
try{
int row =dep_report.getSelectedRow();
String Table_click=(dep_report.getModel().getValueAt(row, 0).toString());
String sql ="select Date_Acquired 'Date Acquired',Serial_Number 'Serial Number',"
+ " Description 'Description',Cost_Of_Acquisition 'Cost Of Acquisition',"
+ "Monthly_Depreciation 'Monthly Depreciation',Accumulated_Depreciation 'Accumulated Depreciation',Net_Book_Value 'Net Book Value'"
+ ",asset_update.Branch_Area 'Branch Area',Depts_name 'Department Name' ,User 'User',"
+ "Status 'Status' from items,asset_update where items.items_No = asset_update.items_No &&'"+Table_click+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()){
String add1 = rs.getString("Monthly Depreciation");
MonthlyDep.setText(add1);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
I would really appreciate the help thank you.
In your sql
where items.items_No = asset_update.items_No &&'"+Table_click+"'";
&& wont work for sql and you might need
where items.items_No = asset_update.items_No and items.someThing= '"+Table_click+"'";
Please use Java naming conventions and give proper names to things Table_click is a horrible variable name.
But can you describe what is in your table model in the 1st column of the selected row?
You seem to append that to your query and if it does not contain a valid SQL part, this will not work well with your statement. In a where clause you usually check a column against a value. I doubt that your table model has this written there, more likely you just have the value in your table model at this position.
Also make sure to properly use prepared statements. Never put the values directly in the SQL string you create or you create the perfect entry point for SQL injection. Assign the values instead once you have created the statement with something like this: pst.setString(1, Table_click);

Prepared statement - using a function as part of the where clause

I am working with a Java prepared statement that gets data from an Oracle database. Due to some performance problems, the query uses a "virtual column" as an index.
The query looks like this:
String status = "processed";
String customerId = 123;
String query = "SELECT DISTINCT trans_id FROM trans WHERE status = " + status + " AND FN_GET_CUST_ID(trans.trans_id) = " + customerId;
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(query);
ps.execute();
...
} catch (...)
This does not work. Having the function as part of the where clause causes a SQLException. I am aware of CallableStatement, and know I could use that first and then concatenate the results. However, this table uses FN_GET_CUST_ID(trans_id) as part of it's index. Is there a way to use a prepared statement with a database function as a query parameter?
Never concatenate arguments for the SQL into the String. Always use placeholders (?) and setXxx(column, value);.
You'll get the same error if you'd run the SQL in a your favorite DB tool. The problem is that Oracle can't use the function for some reason. What error code do you get?
If Customer ID is numeric keep in int not in String. Then try doing the following:
String query = "SELECT DISTINCT trans_id FROM trans WHERE status = ? AND FN_GET_CUST_ID(trans.trans_id) = ?";
ps = conn.prepareStatement(query);
ps.setString(1, status);
ps.setInt(2, customerId);
ps.execute();
Besides other benefits of prepared statement you won't have to remember about string quotations (this causes your error most likely) and escaping of the special characters.
At the first glance, the query seems to be incorrect. You are missing an apostrophe before and after the usage of status variable (assuming that status is a varchar column).
String query = "SELECT DISTINCT trans_id FROM trans
WHERE status = '" + status + "' AND FN_GET_CUST_ID(trans.trans_id) = " + customerId;
EDIT: I am not from java background. However, as #Aron has said, it is better to use placeholders & then use some method to set values for parameters to avoid SQL Injection.

Categories