I am executing an update and I want to insert the value that is returned from my getter into the my table.
statement.executeUpdate("INSERT INTO my_table " +
"VALUES(myClass.getValue(), 'abcd',now())");
I have tried debugging through and I found that the String value and datetime executes correctly. However it gives me an exception when I am calling my getter. The detail message that it shows is FUNCTION myClass.getValue does not exist.
My imports are in order. Any ideas?
statement.executeUpdate("INSERT INTO my_table " + "VALUES("+myClass.getValue() + ", 'abcd',now())");
Your get-call was interpreted as a String because of the missing ' " '.
Take a look at prepared statements, they are easy to read and use and you don't have to struggle with these problems.
Prepared Statement Version (also a lot more secure because they are preventing SQL Injection):
PreparedStatement pst = yourconnection.prepareStatement("INSERT INTO my_table VALUES(?,?,now())";
pst.setString(1,myClass.getValue());
pst.setString(2,"abcd");
pst.executeUpdate();
This is the SQL that you're trying to execute.
INSERT INTO my_table VALUES(myClass.getValue(), 'abcd',now())
You need to pass valid SQL to the executeUpdate method in order for it to run. Java won't interpolate variables and method calls inside strings for you. You have to either concatenate their values into the SQL string that you pass to executeUpdate, or use Prepared Statements instead.
You need to make a method call to your myClass object, not a string. The string will not be executed, its not code, just words.
statement.executeUpdate("INSERT INTO my_table VALUES(" + myClass.getValue() + ", 'abcd',now())");
I'm going to show you how to do it with prepared statements since the other answers did not show you:
PreparedStatement prepStmt = con.prepareStatement("INSERT INTO my_table VALUES( ? , 'abcd',now())"));
prepStmt.setString(1, myClass.getValue());
prepStmt.executeUpdate();
Notice the ?. It will get replaced by your Java call to myClass.getValue().
Please do not concatenate SQL strings.
Related
Is there a possible way to inject some code in the the following statements (I tried the sleep function and it worked , but i'm looking for a way to get the table's name):
PreparedStatement statement = connection.prepareStatement(
"select password from " + USERS_TABLE_NAME + " where userid = ? and password = ?");
statement.setString(1, username_login);
statement.setString(2, password_login);
Using a prepared statement makes the code safe from SQL injection; the only way to inject some code into that query would be to tamper with USERS_TABLE_NAME somehow. I can't tell much about this as you didn't provide any code related to this, but if it's just a string constant you should be fine.
I read it can be be injectable using the ORDER BY clause !!
The example you showed above is not vulnerable to injection in the ORDER BY clause. The query doesn't even have an ORDER BY clause, or any string concatenation that could append an ORDER BY clause to the end of the query.
SQL injection can occur only if you allow untrusted content to modify the SQL query before passing it to the prepare() method.
I'm facing an issue with insertion to SQL database from java code.
I'm using INSERT sql query using the java code to enter the data from XML file to SQL database.
You may suppose column named "Description".
Imagine there is a record in XML which contains apostrophe ('). The program crashes due to the error caused by the apostrophe which is included in the data.
I know that manually we can add another apostrophe and make it work, but imagine data of 10.000 records, how can we handle this issue?
Don't do this (string concatenation):
String sql = "insert into MyTable (description) values ('" + value + "')";
Statement st = connection.createStatement();
st.executeUpdate(sql);
Do do this (prepared statement):
PreparedStatement ps = connection.prepareStatement(
"insert into MyTable (description) values (?)"
);
ps.setString(1, value);
pt.executeUpdate();
The value will get correctly escaped for you. Not only does this protect against mishaps like the one you mentioned, it also helps defend you from SQL injection attacks.
Humorous illustration:
Source
You have two options, you should use PreparedStatement and bind your parameter(s). Or, if you really, really, want - you could use StringEscapeUtils.escapeSql(str).
I'm trying to insert data into my MYSQL databse. I want to insert an int into the database which I have no problem doing. However, I want to INSERT INTO (VALUES) WHERE. I get a MYSQL syntax error when I try this.
I can INSERT and SELECT WHERE as long as they are in two seperate statements. Here is my code:
String query = ("INSERT INTO `accounts` (inventory) " + "VALUES ('"
+ Inventory.inventory + "') WHERE username='" + Frame.username
+ "' and password = '" + Frame.password + "'");
Basically, an INSERT statement can not have a WHERE clause. I am thinking that you want to UPDATE a certain record, eg
UPDATE accounts
SET inventory = 'valueHere'
WHERE userName = 'userHEre' AND password = 'passHere'
The only time an INSERT statement can have a WHERE clause is when you are inserting records from the result of a SELECT statement, eg
INSERT INTO tableName (col1, ..., colN)
SELECT col1, ..., colN
FROM table2
// WHERE ..your conditions here..
As a sidenote, your current coding style is vulnerable with SQL Injection. Consider using PreparedStatement.
Basic example of a PreparedStatement
String updateString = "UPDATE accounts SET inventory = ? WHERE userName = ? AND password = ?";
PreparedStatement updateStmt = con.prepareStatement(updateString);
updateStmt.setString(1, Inventory.inventory);
updateStmt.setString(2, Frame.username);
updateStmt.setString(3, Frame.password);
updateStmt.executeUpdate();
JDBC PreparedStatement
MySQL INSERT Syntax does not support the WHERE clause so that's why you have a syntax issue. Maybe you're looking for an UPDATE :
UPDATE [LOW_PRIORITY] [IGNORE] tbl_name
SET col_name1=expr1 [, col_name2=expr2 ...]
[WHERE where_definition]
[ORDER BY ...]
[LIMIT row_count]
Not a direct answer but more of a best practice....
You should avoid doing this type of string concatenation for any sql. You vulnerable to sql injection and it does not scale well. Instead you should look at using JdbcTemplates or NamedJdbcTemplate using the opensource spring framework.
The WHERE is not applicable in INSERT INTO Syntax. You want insert a new row in the table, and you should add the username and password as well as Inventory.inventory in VALUES set.
I have problems running this sql statement. It works fine if I run it in mysql but in java I get this error:
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near '' at line 1
The database has an id(pk) autogenerated, varchar, int, varchar;
Can someone help me?
int i = statement.executeUpdate("INSERT INTO sala values('','"+ nume.getText() + "', "+ Integer.parseInt(capacitate.getText())+ ", '" + sunet.getText()+"'");
Don't just try to fix this code by tweaking the SQL as per adarshr's answer. You have a fundamental security problem here which you should fix right now. You're open to SQL injection attacks due to including user data directly in your SQL.
You should use a PreparedStatement, with the parameters declared as placeholders in the SQL, but then given values separately. Exactly how you'll do that will depend on your JDBC provider, but it'll look something like this:
// TODO: Fix the column names, and close the statement in a try/finally block
PreparedStatement pst = conn.prepareStatement(
"INSERT INTO sala (nume, capacitate, sunet) VALUES (?, ?, ?)");
pst.setString(1, nume.getText());
pst.setInt(2, Integer.parseInt(capacitate.getText()));
pst.setString(3, sunet.getText());
pst.executeUpdate();
Note that if you can get capacite in a way which doesn't require integer parsing, that would be good. Otherwise, consider using NumberFormat which is more locale-friendly. Also note that I've added the column names into the SQL to make this more robust in the face of schema changes.
You haven't closed your query.
int i = statement.executeUpdate("INSERT INTO sala values('','"+ nume.getText() + "', "+ Integer.parseInt(capacitate.getText())+ ", '" + sunet.getText()+"')");
^
But more than all this, you must use PreparedStatement as Jon suggested below.
I've read many threads regarding this topic, but everybody point to the character set in the database.
I'm using strings with special characters like 'ñ' and I'm not able to set them right in the database. As you may guess, the characters are changed to '?'.
The thing is that using this statement, I get it RIGHT:
stmt = con.prepareStatement("INSERT INTO LONG_CODES_TABLE (TIMESTAMP, TABLE_NAME, CODE__C, CODE_DESC)
VALUES (GET_TIMESTAMP, 'MUNICIPIOS', '" + municipio + "', '" + municipio + "') ");
And just in the same database and table, without changing anything, if I use the following I get the '?' character in the DB:
stmt = con.prepareStatement("INSERT INTO LONG_CODES_TABLE (TIMESTAMP, TABLE_NAME, CODE__C, CODE_DESC)
VALUES (GET_TIMESTAMP, 'MUNICIPIOS', ?, ?) ");
stmt.setString(1, municipio);
stmt.setString(2, municipio);
So, the character problem is happening ONLY if I use setString.
Any ideas?
EDIT: The value of the 'municipio' variable is, for example: 'ABADIÑO'.
Later, I can check the differences between doing it on way or the other by asking for that value with an sql statement, for example:
select * from long_codes_table
where table_name = 'MUNICIPIOS' and code__c = 'ABADIÑO'
One way I get the result row. The other way, I don't.
Thank you.
I had that behaviour, too. On top of that I observed that this error did not occur when the application was started from the IDE. That's how I realized that in the JVM - attributes, the one for the encoding was missing.
java %vm-opts% %clspth% -Dfile.encoding=UTF-8 ...