JDBC and MS-Access problem - java

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 '*'?

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();

Updated: Problem with executing SQL query from 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.

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.

Running PreparedStatement with Like clause with wildcard

I'm trying to execute following SQL query where it tries to find results that matches the column2 values ending with abc
PreparedStatement stmt = conn.prepareStatement("SELECT column1 FROM dbo.table1 WHERE column2 LIKE ?");
stmt.setString(1, "%" +"abc");
But it returns nothing even though there is a matching value. This only happens with SQL Server. Same query with informix database returns correct results. Anyone has an idea about what causing this to behave differently?
Is this due to an issue in how PreparedStatement creates the SQL query for SQL Server?
Edit
I found out this happens when the data in the column which i perform the like contain space. eg: when the column contains "some word" and if i perform the search by stmt.setString(1, "%" + "word"); it won't return a matching result but if i perform the same on for "someword" it would return the matching result
SQL Server accepts wild characters in the LIKE clause within the single quotation marks, like this ''.
A sample SQL query:
SELECT NAME FROM VERSIONS WHERE NAME LIKE 'Upd%'
The query above will yield you results on SQL Server. Applying the same logic to your Java code will retrieve results from your PreparedStatement as well.
PreparedStatement stmt = conn.prepareStatement("SELECT NAME FROM VERSIONS WHERE NAME LIKE ?");
stmt.setString(1, "Upd%");
I've tested this code on SQL Server 2012 and it works for me. You need to ensure that there are no trailing spaces in the search literal that you pass on to your JDBC code.
Though as a side note, you need to understand that a wildcard % used in the beginning, enforces a full table scan on the table which can deteriorate your query performance. A good article for your future reference.
Hope this helps!
i have same problem,i have done with the CONCATE function for this.
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
ps.setString(1, notes);
ResultSet rs = ps.executeQuery();

JDBC PreparedStatement with "?" in the column name

I am using a JDBC connection to fetch data from an Access database.
The database design is not my control. In the database there are columns that have "?" included in their names, for example: Open?, Paid?, and lots more.
When I try to fetch data with a PreparedStatement it gives me an error. The query is:
SELECT Open? FROM tblJobList WHERE WeekEnding=?
I also tried to use brackets like [Open?], but the result is the same.
The error I receive is "Too few parameters ..." as I am pushing only one parameter into the PreparedStatement.
I can not use normal statement because of WeekEnding=? as this value is a Timestamp and I could not manage to work it with Statement. Only prepared statement works here.
Can anyone tell me how to use these kind of column names in a PreparedStatement?
use the " character
"SELECT \"Open?\" FROM tblJobList WHERE WeekEnding=?"
tested this against oracle and appears to work with mssqlserver
How to select a column in SQL Server with a special character in the column name?
Just to update this for current technologies:
While the JDBC-ODBC Bridge and Access ODBC were unable to handle a PreparedStatement with a column name containing a question mark, the UCanAccess JDBC driver handles it just fine, as can be confirmed with the following code:
String connectionUrl = "jdbc:ucanaccess://C:/Users/Public/UCanAccessTest.accdb";
Connection conn = DriverManager.getConnection(connectionUrl);
String sql = "SELECT ID, [Open?] FROM tblJobList WHERE WeekEnding=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDate(1, java.sql.Date.valueOf("2016-01-01"));
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.printf("%d: %s%n", rs.getInt("ID"), rs.getBoolean("Open?"));
}
conn.close();
For more information on UCanAccess, see
Manipulating an Access database from Java without ODBC
I am not sure but you can try // to escape the special meaning of ? and to use it as a normal character. Like:
"SELECT Open//? FROM tblJobList WHERE WeekEnding=?"
You can get something similar to your problem here:
Round bracket in string with JDBC prepared statement
Escaping quotes in MSSQL is done by a double quote, so a '' or a "" will produce one escaped ' and ", respectively.

Categories

Resources