Updated: Problem with executing SQL query from Java - java

Updated:
so as per the suggestions i changed all the column name to strings and added prepared statements-
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/minor","root","alphabet")) {
Statement st = conn.createStatement();
PreparedStatement stmt= conn.prepareStatement("select * FROM ? where name=? ;");
PreparedStatement stmt2= conn.prepareStatement("select * FROM ? where name=? ;");
stmt.setString(1, day_1);
stmt.setString(2, faculty1);
stmt2.setString(1,day_1);
stmt2.setString(2, faculty2);
ResultSet rs=stmt.executeQuery();
ResultSet rs1= stmt.executeQuery();
The day and faculty is retrieved from input screen, the queries work just fine in mysql workbench but the 'select' keyword goes missing when i try to run it from Java, see the following error-
The faculty1, faculty2 is retrieved from the following-
The database looks like this-

I would recommend to use PreparedStatement instead of Statement, then at least you can bind your variables;
You query select from time_interval from day_selected is not correct, I don't think that it will execute anywhere, you need to have something between select and from, and not two from in one statement.

Related

error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? or tel=?' at line 1

Here's my query:
select *
from reg
where indexno=?
or tel=?
And here's my code:
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://url","unam","pass");
String query = "select * from reg where indexno= ? or tel=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, in.getText());
ps.setString(2, tl.getText());
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
Let's take a closer look at what your code is doing.
Connecting to the database:
Connection con =DriverManager.getConnection("jdbc:mysql://url","unam","pass");
Creating the SQL query:
String query = "select * from reg where indexno= ? or tel=?"`;
Creating a prepared statement:
PreparedStatement ps = con.prepareStatement(query);
Setting some bind parameter values:
ps.setString(1, in.getText());
ps.setString(2, tl.getText());
Creating a whole new non-prepared statement (wait, what? Why are we not using the prepared statement we spent some time creating?):
Statement st = con.createStatement();
Using the new non-prepared statement to execute the SQL query.
ResultSet rs = st.executeQuery(query);
As a result of the last two lines, your SQL query is sent straight to the MySQL database. MySQL doesn't understand what the ? marks are for, and hence complains with a syntax error about them.
When handling prepared statements, JDBC drivers will either replace the ? marks with the database's own syntax for bind parameters (unless the database supports ? marks directly, but not all databases do), or put the values directly in the SQL string after suitable escaping of any characters, before they send the SQL to the database. Statements don't support bind parameters, and will just send the SQL string they are given straight to the database.
Your code creates a PreparedStatement and sets two bind parameter values. It seems a shame not to actually use your prepared statement once you've created it. You can get the result set you want out of it by calling ps.executeQuery(). There is no need for the separate Statement you created by calling connection.createStatement().
The fix therefore is to remove the last two lines of the code in your question and add the following line in place of them:
ResultSet rs = ps.executeQuery();

SQL error with JDBC, parameter out of range [duplicate]

I am trying to use the java mysql library but I am having issues using a prepared statement. I am not sure what I am missing. Below is what I have with the MYSQL error attempting to use the prepared statement.
String query = "SELECT id, clicks FROM mailer.links WHERE campaign_id=?";
try {
preparedStatement = connect.prepareStatement(query);
preparedStatement.setInt(1, campaignId);
preparedStatement.execute();
Statement st = connect.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
I am getting the following error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
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
It works if I do "campaign_id=" + campaignId , but is a SQL injection waiting to happen.
Try this
ResultSet rs = preparedStatement.executeQuery();
PreparedStatement method executeQuery() itself returns a ResultSet object
So assign this to a ResultSet object
ResultSet rs = preparedStatement.executeQuery();
Error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
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
And this error happens because When
ResultSet rs = st.executeQuery(query);
This statement executes it can't find any value in ? operator.
so your query remains this "SELECT id, clicks FROM mailer.links WHERE campaign_id=?"; and this throws a MySQL Syntax Exception.

SQL statement not adding the single quotes ( ' ')

Im writing a java program and I have a SQL statement that currently is outputting wrong:
so the code is:
String sql = "SELECT Name from Users WHERE Name LIKE "+t;
and the Output is:
SELECT Name from Users WHERE Name LIKE David
But I need it to be with single quotes how can I add that to be like:
SELECT Name from Users WHERE Name LIKE 'David'
how can I add those quotes?
Many thanks for the help
This is a very common mistake. I'm guessing you are using Statement class to create your query and executing it.
I'd like to suggest that you use prepared statements. It'll since your issue and help you with further issues.
PreparedStatement ps = yourconn.prepareStatement("select name from users where name like ?");
ps.setString(1,yoursearchedusername);
ResultSet rs = ps.executeQuery();
This will add your quotes. Plus it will prevent from sql injection attacks in future.
Your current query will also cause issues of your actual query has ' or ? Or any other sql wild card. Prepared statement avoids all these issues and helps with performance by having the sql already compiled and stored at db layer (if enabled)
Use a prepared statement to prevent sql injections.
String searchedName = "cdaiga";
String sql = "SELECT Name from Users WHERE UPPER(Name) LIKE '%?%'";
PreparedStatement preparedStatement = dbConnection.prepareStatement(sql);
preparedStatement.setString(1, (searchedName!=null? searchedName.toUpper(): ""));
// execute the SQL stetement
preparedStatement .executeUpdate();
ResultSet rs = preparedStatement.executeQuery();
// print the results if any is returned
while (rs.next()) {
String name= rs.getString("Name");
System.out.println("name: " + name);
}
Note that a case insensitive search would be appropriate.

Java does not run prepare statements with parameter

I am using PreparedStatement to query my table. Unfortunately, I have not been able to do so.
My code is as simple as this:
PreparedStatement preparedStatement = connection.prepareStatement(
"Select favoritefood from favoritefoods where catname = ?");
preparedStatement.setString(1, "Cappuccino");
ResultSet resultSet = preparedStatement.executeQuery();
The error thrown is java.sql.SQLException: ORA-00911: invalid character. As if it never run through the parameter given.
Thanks for your time. I've spend a day to debug this yet still unsuccessful.
As mention by Piyush, if I omit the semicolon at the end of statement, a new error is thrown. java.sql.SQLException: ORA-00942: table or view does not exist. But I can assure you this table is indeed exist.
UPDATE
shoot. i edited the wrong sql. now it is successful. thx for your time.
Do you get this error if you try binding values from the shown sql and excute it from the SQL prompt or any SQL editor?
Make sure your query is not having semicolon (";") at the end of it or anywhere in the query.
try giving it this way..
String query="Select favoritefood from favoritefoods where catname = ?";
preStat = conn.preparedStatement(query); // conn is the connection object
preStat.setString(1,"Cappuccino");
ResultSet resultSet=preStat.executeQuery();

JDBC and MS-Access problem

I'm trying to connect to an MSAccess database and retrieve some data.
With simple examples all runs well but if i'm going to use some
where clauses i get no data.
This example is ok:
PreparedStatement stm = con.prepareStatement("SELECT A.* FROM A");
ResultSet rs = stm.executeQuery();
rs.next();
The next example get no rows:
PreparedStatement stm = con.prepareStatement("SELECT A.* FROM A WHERE (((A.Name) LIKE ?))");
stm.setString(1,"*");
ResultSet rs = stm.executeQuery();
rs.next();
I don't know where the error lies: in the driver or in the sql syntax.
The sql statement is taken from the query builder in MSAccess.
All what is a little bit more complex in a where clause is a really hard to figure out. Is there any documentation reagrding sql syntax of MSAccess ?
Update
Yes in the jdbc sql statement i have to use "SQL standard" % wildcard while the Access sql builder is using *. Now going to query with dates =8-o
For the like statement to work you have to put the parameter between %:
PreparedStatement stm = con.prepareStatement("SELECT A.* FROM A WHERE (((A.Name) LIKE ?))");
stm.setString(1,"%like text%");
Do you, by any chance, mean the SQL wildcard character, '%', instead of '*', or are you literally looking for the character '*'?

Categories

Resources