Specifying a variable name in QUERY WHERE clause in JDBC - java

Could someone please give me a link on how to create a query in JDBC that gets a variable name in the WHERE statement, or write an example, to be more specific, my code looks something like this:
private String getLastModified(String url) {
String lastModified = null;
ResultSet resultSet;
String query = "select LastModified from CacheTable where " +
" URL.equals(url)";
try {
resultSet = sqlStatement.executeQuery(query);
}
Now I need the syntax that enables me to return a ResultSet object where URL in the cacheTable equals url from the method's argument.
thanks

The easiest way would be
String query = "select LastModified from CacheTable where url = '" + url +"'";
You should use bind variables though:
String query = "select LastModified from CacheTable where url = ?";
prepStmt = conn.prepareStatement(query);
prepStmt.setString(1, url);
rs = prepStmt.executeQuery();

To take it one step further you should really use DBUtils from apache-commons or Sping JDBC framework. A lot of JDBC work is mundane and error prone due to the number of steps involved with it. Both links have working examples for you to get started.
These helper libraries will make your life much more comfortable :-).

To clear a misconception: JDBC and SQL are two entirely different things. Databases only understand the SQL language. It's a (semi)standard which you can learn here. JDBC is just a Java API which enables you to execute SQL language using Java code. Nothing less, nothing more. JDBC is not a Java way of writing SQL language or so. It's just the messenger between Java code and the database. You can learn JDBC here.
That said, yes, the PreparedStatement is the way to go to set values in a SQL query. It not only eases setting fullworthy Java objects in a SQL string using the setXXX() methods, but it also saves you from SQL injection attacks.

Related

How to show date between start date and end date in ms access

i have error in my code
net.ucanaccess.jdbc.UcanaccessSQLException:
UCAExc:::3.0.7 unexpected token: 2016 required: AND
and this is my code
try{
String sql = "Select id,nama,grup,tanggal from kuli where tanggal between '"+ctgl.getText()+"' 'AND' '"+ctgl1.getText()+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e)
{
System.out.println(e);
}
The SQL should be like this:
String sql = "Select id, nama, grup, tanggal from kuli where tanggal between #" + ctgl.getText() + "# and #" + ctgl1.getText() + "#";
and ctgl.getText() and ctgl1.getText() must return strings formatted as: 2016/11/05
You are not passing proper date for ctgl.getText(), because which the SQL query is failed to retrieve the data. Also, do not use the 'AND' with quotes.
You need to ensure that you are passing the correct date format.
Also, it is NOT recommended to use the prepareStatement like this (i.e., in your code formed the sql using string concatenations) which will allow the cross site scripting, rather the best practice is to use prepareStatement.setString(), setDate(), etc.. methods,
You can look here about cross site scripting.
Two problems:
It looks like your SQL syntax is broken. There should not be quotes around the AND keyword.
You should not be embedding the parameter values into the SQL like that. Instead, you should be using a PreparedStatement and place-holder parameters.
Using PreparedStatement has a number of advantages:
It means that you don't need figure out how to quote values.
It means that you don't need figure out the correct syntax for date/time literals.
It means that you don't need to worry about SQL injection attacks.
The last one is really important if the parameter values come from a source that you cannot completely trust.
More information:
SQL injection
SQL Injection Prevention Cheat Sheet

Getting Incorrect return in java accessing sql database

This is the code im using in java to query the database
connect = DriverManager.getConnection (url, "user", "pass");
state = connect.createStatement();
String meetID = "SELECT GamerTag FROM backup";
ResultSet rs = state.executeQuery(meetID);
while(rs.next()){
System.out.println(rs.toString());
}
Im not getting the values of the row in the database im getting this instead
com.mysql.jdbc.JDBC4ResultSet#108137c9
You're printing the result of the toString method of the Recordset object, which appears to print out the object's name and hashcode.
Instead, try to print the value of a column. Perhaps using getString:
System.out.println(rs.getString("GamerTag"));
The documentation for Java's recordset looks confusing, you might be better off searching for examples.
What do you expect rs.toString() should do it will just print the hash of the resultsetObject if you want to get the column values you should do this way
while(rs.next()){
System.out.println(rs.getString("yourFirstColumnName")+" "+
rs.getString("yourSecondColumnName")+" "+
rs.getString("yourThirdColumnName"));
}
Really you should use PreparedStatement. In your case though you are not using any parameterizedQuery but One of the major benefits of using PreparedStatement is better performance. PreparedStatement gets pre compiled.
In database and there access plan is also cached in database, which allows database to execute parametric query written using prepared statement much faster than normal query because it has less work to do. You should always try to use PreparedStatement.
So you can do something like this
String query = "SELECT GamerTag FROM backup"
PreparedStatement st =connect.prepareStatement("query");
ResultSet rs = st.executeQuery();

Trouble with SQL querys

I'm having trouble with an SQL query. The problem is that I'm querying an external database of enterprise names and some names are like "Martha's" (include apostrophes). And because I'm querying from an android app, the query string looks like:
String query = "Select * from Advertiser where AdvName= '" + name + "';";
So is there anyway I could ignore or change the apostrophes in the query?
Thanks in advance!
That's one of the reasons why you should always use prepared statements when executing parameterized queries:
String sql = "select * from Advertiser where AdvName = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, name);
ResultSet rs = stmt.executeQuery();
The JDBC driver will escape the quotes for you, and this will also prevent SQL injection attacks.
Prepared statements also have performance advantages when you must execute the same query several times but with different parameters.
Read more about prepared statements in the JDBC tutorial.
Side note: you shouldn't have a ; at the end of your query.
In PLSQL you should use double '' in the input-field, meaning, Martha's => Martha''s:
String query = "Select * from Advertiser where AdvName= 'Martha''s';";
Important Remark:
For security purposes (to avoid sql injection) you should avoid creating queries the way you do, better use prepared-statement and set the parameters like this:
String query = "Select * from Advertiser where AdvName= ? ";
PreparedStatement st = conn.prepareStatement(query);
st.setString(1,name);

PreparedStatement performance tuning

Is there any way to improve performance of prepared statements? It's about many select queries. I do the queries like this way:
String query = "SELECT NAME, ADDRESS "
+ "FROM USERS "
+ "where ID = ? "
+ "group by NAME, ADDRESS";
PreparedStatement pstmt = connection.prepareStatement(query);
for(long id: listIDs){
pstmt.setLong(1, id);
ResultSet rs = pstmt.executeQuery();
...
}
The database is MySQL.
It's the server that prepares the queries (that's why you need a connection). To improve performance of prepared statements you have to tune the DB server itself (indexes, etc...).
Another way, is writing queries that only get the results you want.
Another idea is to cache in client side the data you know you'll be using a lot, this way you won't be querying the DB for the same data again and again.
Two suggestions:
Make sure the ID field is indexed.
Combine many small queries into one, for example by using WHERE ID IN (...).
For a more detailed discussion of the latter, see Batching Select Statements in JDBC.
You might also want to investigate whether your JDBC driver supports statement caching. I know oracle's JDBC driver does support.

Created a Java Web app/MySql app

Started coming up with a java web app for online user interaction. Decided to use a MySql DB for data storage. I have already created the tables with the proper/expected data types. My question is I always thought the next step would be to creat stored procedures like Search/Add/Delete/etc.. that the user could envoke from the page. So in my java code I could just call the procedure ex:
CallableStatement cs;
Try
{
String outParam = cs.getString(1); // OUT parameter
// Call a procedure with one in and out parameter
cs = connection.prepareCall("{call SearchIt(?)}");
cs.registerOutParameter(1, Types.VARCHAR);
cs.setString(1, "a string");
cs.execute();
outParam = cs.getString(1);
}
catch (SQLException e) {
}
but if my application was not in the need for stored procedures because the user actions would be simple enough to execute simple tedious queries. How could I set up my Java and Sql code to handle that. Could I just have the "Select" or "Update" statements in my code to manipulate the data in my MySQL DB. If so how would that syntax look like?
This URL has documentation on using prepared statements which is what you want to use to avoid security flaws (SQL Injection and such).
http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html
here's an example from that page
PreparedStatement updateSales = connection.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate():
Just use Statement, or PreparedStatement.
http://download.oracle.com/javase/1.4.2/docs/api/java/sql/Statement.html
In a similar way to what you did, just call :
Statement stm = Connection.createStatement();
then execute your SQL :
stm.execute("SELECT * FROM MYTABLE");
grab the resultset and check out the results.
Beware though - this is bad bad as far as security goes - as others have mentioned, PreparedStatements are a bit more secure, but still not 100%.
To be honest, although basic JDBC is pretty simple, I really hate all the SQL strings littered around your code. If you want something a bit more elegant have a quick look at hibernate - it hides all the hackiness from you, and is also pretty easy to setup.

Categories