MySQL Query in Java Eclipse - java

I am writing a program, where the user will be receiving instructions in different languages. I have the tables structures by language, so based on the user's language user settings, the corresponding language table will be selected. However, I keep getting errors from the following code.
String query2 = "select * from ? where instruction_id = ?";
PreparedStatement pst2 = connection.prepareStatement(query);
pst2.setString(1, user_config.language);
pst2.setString(2, instruction_id);
ResultSet rs2 = pst2.executeQuery();
Can someone explain why the above code is not working?

I ended up using string concatenation for the table name.
String query2 = "select * from " + user_config.language + " where instruction_id = ?";
PreparedStatement pst2 = connection.prepareStatement(query2);

Related

Can't find an Error in SQL update statement

I'm working in one quiz game. There is question maker window. Which works good for saving question. But when want update one of text Field and press save, than error is happening. something is wrong with syntax?!
void insertCell(String tableNamer, String column, String value, int id) throws ClassNotFoundException, SQLException{
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:file:C:/Users/Juris Puneiko/IdeaProjects/for_my_testings/src/sample/DB/Questions/For_Private/Easy", "Juris", "1");
PreparedStatement ps = conn.prepareStatement("UPDATE ? SET ? = ? where ID = ?");
ps.setString(1, tableNamer);
ps.setString(2, column);
ps.setString(3, value);
ps.setInt(4, id);
ps.executeUpdate();
ps.close();
conn.close();
}
org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "UPDATE ?[*] SET ? = ? WHERE ID = ? "; expected "identifier"; SQL statement:
UPDATE ? SET ? = ? where ID = ? [42001-196]
What is this >>> [*]?
What does it mean?
String sql = "UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, value);
ps.setInt(2, id);
ps.executeUpdate();
ps.close();
conn.close();
The placeholders can only be used for values in most SQL databases, not for identifiers like table or column names:
"UPDATE myTable SET myCol = ? where ID = ?" -- OK
"UPDATE ? SET ? = ? where ID = ?" -- not OK
The reason is that those parameters are also used for prepared statements, where you send the query to the database once, the database "prepares" the statement, and then you can use this prepared statement many times with different value parameters. this can improve DB performance because DB can compile and optimize the query and then use this processed form repeatedly - but to be able to do this, it needs to know names of the tables and columns involved.
To fix this, you only leave the ?s in for the values, and you concatenate the tableNamer and column manually:
"UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?"
Keep in mind though that by doing this, tableNamer and column are now potentially vulnerable to SQL injection. Make sure that you don't allow user to provide or affect them, or else sanitize the user input.

PreparedStatement execution says MySQLSyntaxErrorException although works in MySQL console

I've written the following code (snippet):
conn = Pooling.getDataSource().getConnection();
String databaseName = Configuration.getDatabaseName();
String sql = "SELECT * FROM " + databaseName + ".companies WHERE companyemail = ? AND companypassword = MD5(?)";
PreparedStatement prepStat = conn.prepareStatement(sql);
prepStat.setString(1, username);
prepStat.setString(2, password);
System.out.println("LoginService: prepStat = " + prepStat.toString());
ResultSet rs = prepStat.executeQuery(sql);
...
Now, when I execute this, I'm getting a MySQLSyntaxErrorException. The prepStat.toString() prints:
SELECT * FROM dbname.companies WHERE companyemail = 'comp#comp.com' AND companypassword = MD5('passwort')
And a simple copy and paste to SequelPro successfully return a result.
However, the backend still claims that there is an error in the syntax:
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 '? AND companypassword = MD5(?)' at line 1
Maybee I'm blind but I do not see an error here? But what is happening here?
Okay, I found out what the problem was. I used:
ResultSet rs = prepStat.executeQuery(sql);
However, I should have used
ResultSet rs = prepStat.executeQuery();
instead.
Try this:
String sql = "SELECT * FROM '" + databaseName + ".companies' WHERE companyemail=? AND companypassword = MD5(?)";
Notice the single quote before the databaseName variable and after .companies . I think that could be the problem.
Or you could do this:
String sql = "SELECT * FROM ? WHERE companyemail =? AND companypassword = MD5(?)";
PreparedStatement prepStat = conn.prepareStatement(sql);
prepStat.setString(1, databaseName);
prepStat.setString(2, username);
prepStat.setString(3, password);
I believe the problem is at the level of parsing the databaseName to the prepared statement.

SQLite select from LIKE statement not working?

When I view the database and run this query I get results as expected.
SELECT * FROM users WHERE options LIKE '%[-15,-3]%';
However when I use a prepared statement as seen below, the uuid is null.
String opt = "[-15,-3]"; //example
PreparedStatement ps = SQLite.connection.prepareStatement(
"SELECT * FROM users WHERE options LIKE '%" + opt + "%'"
);
ResultSet rs = ps.executeQuery();
String uuid = null;
while (rs.next()){
uuid = rs.getString("member");
}
rs.close();
ps.close();
if(uuid != null){
System.out.println("not null: " + uuid);
return Database.getUser(UUID.fromString(uuid);
}
For the code above, nothing is returned in the result set. Which is very strange because I used the same query with an SQLite viewer and it returned the proper rows. How can I solve this? I don't see an issue.
UPDATE
When I directly use "SELECT * FROM factions WHERE claims LIKE '%[-15,-3]%'" in the prepared statement instead of the variable, it works fine. Why can't I use a string variable? I've checked the variable and it prints to console fine.
I solved it after a lot of trial and error, turns out I should've been using a ? and set the string.
PreparedStatement ps = SQLite.connection.prepareStatement(
"SELECT * FROM users WHERE options LIKE ?"
);
ps.setString(1, "%" + opt + "%");

equivalent of String.Format() in Java

I have this peace of code :
String query = "SELECT * FROM utilisateurs WHERE pseudo = '" + pseudo.getText()+ "' AND password = '" + new String(password.getPassword()) + "'";
My question is : isn't there any other method to concat these variables with the string ?
In C# I was using the method String.Format() method as :
String query = String.Format("SELECT * FROM utilisateurs WHERE pseudo = '{0}' AND password = '{1}'", pseudo.getText(), new String(password.getPassword()));
String.format() can be used to format Strings, Javadoc.
public static String format(String format, Object... args)
Returns a formatted string using the specified format string and arguments.
However when it comes to building SQL query strings the preferred way is to use PreparedStatement (Javadoc) as it:
protects you from SQL injection
allows the database to cache your query (build the query plan once)
Your code using a PreparedStatement might look like below:
final PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM utilisateurs WHERE pseudo = ? AND password = ?");
pstmt.setString(1, pseudo.getText());
pstmt.setString(2, new String(password.getPassword()));
final ResultSet rs = pstmt.executeQuery();
As others have said, String.format is the direct equivalent, but you should use a PreparedStatement instead. From the documentation:
In the following example of setting a parameter, con represents an
active connection:
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES
SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)
Using a PreparedStatement instead of String.format will protect your code from SQL injection.
Java has similar method to format your strings. String.format()
However, if you choose to use PreparedStatement, you can read the documentation here
From the documentation:
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)
To answer your question directly, as others have mentioned as well, use String.Format, here is a good resource for that: How to use java.String.format in Scala?.
However, in this particular example, the real answer is not to do string substitution, but to use arguments in the SQL statement.
Something like:
query =
String query = "SELECT * FROM utilisateurs WHERE pseudo = ? AND password = ?";
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, pseudo.getText());
ps.setString(2, password.getPassword());
ResultSet rs = ps.executeQuery();

Assigning resultset column value to a variable for use in another SQL Statement?? Java

I am creating a data centric webservice in Java for deployment to Glassfish. All of my methods so far are working correctly except for one.
I am attempting to assign a value from a result set to a variable to use in another SQL statement as per the below code. I am not sure if its possible, or if perhaps my SQL is wrong, but any ideas would be appreciated.
ResultSet rset1 = stmt1.executeQuery("SELECT *
FROM WorkOrder
WHERE WorkOrderID = '"+workOrderID+"'");
Integer custID = rset1.getInt(3);
ResultSet rset2 = stmt2.executeQuery("SELECT *
FROM Customer
WHERE CustID = '"+custID+"'");
Integer quoteID = rset1.getInt(2);
ResultSet rset3 = stmt3.executeQuery("SELECT *
FROM Quote
WHERE QuoteID = '"+quoteID+"'");
What you posted can and should be done in a single query - less complex, and less [unnecessary] traffic back & forth with the database:
SELECT q.*
FROM QUOTE q
WHERE EXISTS (SELECT NULL
FROM CUSTOMER c
JOIN WORKORDER wo ON wo.custid = c.custid
WHERE c.quoteid = q.quoteid
AND wo.workorderid = ?)
The reason this didn't use JOINs is because there'd be a risk of duplicate QUOTE values if there's more than one workorder/customer/etc related.
Additionally:
Numeric data types (quoteid, custid, etc) should not be wrapped in single quotes - there's no need to rely on implicit data type conversion.
You should be using parameterized queries, not dynamic SQL
You foget to invoke ResultSet.next().
if(rset1.next())
{
Integer custID = rset1.getInt(3);
....
}
The note provided by OMG Ponies was really important to take note of, but does not really answer the question. AVD was also correct. I've cleaned it up a bit and included prepared statements. Please use prepared statements. They will help you sleep at night.
PreparedStatement pstmt1 = con.prepareStatement(
"SELECT * FROM WorkOrder WHERE WorkOrderID = ?");
PreparedStatement pstmt2 = con.prepareStatement(
"SELECT * FROM Customer WHERE CustID = ?");
PreparedStatement pstmt3 = con.prepareStatement(
"SELECT * FROM Quote WHERE QuoteID = ?");
pstmt1.setInt(1, workOrderId)
ResultSet rset1 = pstmt1.executeQuery();
// test validity of rset1
if(rset1.next()) {
pstmt2.setInt(1, rset1.getInt(3))
ResultSet rset2 = pstmt2.executeQuery();
// test validity of rset2
if(rset2.next()) {
pstmt3.setInt(1, rset1.getInt(2))
ResultSet rset3 = pstmt3.executeQuery();
}
}

Categories

Resources