i am passing date in sql query using java.Below is my code that retrieve no result.
java.sql.Date d1=java.sql.Date.valueOf(startDate);
java.sql.Date d2=java.sql.Date.valueOf(enddate);
String url= "jdbc:jtds:sqlserver://"+serverName+"/"+database;;
String driver = "net.sourceforge.jtds.jdbc.Driver";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url);
System.out.println("Connected to the database!!! Getting table list...");
Statement sta = conn.createStatement();
String Sql = "Select INDEX from Table where DATE between "+d1+" and "+d2;
System.out.println("sql="+Sql);
rs = sta.executeQuery(Sql);
}
} catch (Exception e) {
e.printStackTrace();}
Query returns no row because date should be passed as '2015-02-28' but query treats date as 2015-02-28 without single quote.Please suggest.
Creating SQL statements by concatenating strings together makes your software vulnerable to SQL injection (if the values of the variables come from user input).
You should use PreparedStatement instead:
PreparedStatement sta =
conn.prepareStatement("Select INDEX from Table where DATE between ? and ?");
sta.setDate(1, d1);
sta.setDate(2, d2);
rs = sta.executeQuery(Sql);
Add single quotes
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2+"'";
but the best option would be using PreparedStatement.
Try it like so:
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2 + "'";
That being said, you should look into PreparedStatements.
You have multiple issues in the query
INDEX is a reserved word and you need to escape it using backticks http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Date should be used within quotes
So the query should be
String Sql = "Select `INDEX` from Table where DATE between '"+d1+"' and '"+d2+"'";
Replace Your Query with
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2+"'";
I suggest you to use PreparedStatement Instead
String query="Select INDEX from Table where DATE between ? and ?";
PreparedStatement ps=con.prepareStatement(query);
ps.setDate(1,d1);
ps.setDate(2,d2);
ps.executeQuery();
Related
I'm trying to insert a record inside my table but I cannot insert any values into the Date column.
This is the code I use to make an insert:
Connection connection = DatabaseConnection.getInstance().getConnection();
ResultSet result = null;
try
{
Statement statement = connection.createStatement();
statement.executeUpdate(query,Statement.RETURN_GENERATED_KEYS);
result = statement.getGeneratedKeys();
} catch (SQLException e)
{
e.printStackTrace();
}
finally
{
return result;
}
How I call this function:
String authorName = "Paul"
String authorSurname = "Mac"
DateTimeFormatter f = DateTimeFormatter.ofPattern( "yyyy-MM-dd" ) ;
LocalDate date = LocalDate.parse ( "2017-09-24" , f );
"Insert into autore(nome_autore, cognome_autore, datanascita) values('"+authorName+"', '"+authorSurname+"', "+date+")")
The fullstack trace I get:
org.postgresql.util.PSQLException: ERROR: column "datanascita" is of type date but expression is of type integer
Suggerimento: You will need to rewrite or cast the expression.
Posizione: 90
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2676)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2366)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:356)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:496)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:413)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:333)
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:319)
at org.postgresql.jdbc.PgStatement.executeUpdate(PgStatement.java:1259)
at org.postgresql.jdbc.PgStatement.executeUpdate(PgStatement.java:1240)
at projectRiferimentiBibliografici/com.ProjectRiferimentiBibliografici.DatabaseConnection.QueryManager.executeUpdateWithResultSet(QueryManager.java:113)
at projectRiferimentiBibliografici/com.ProjectRiferimentiBibliografici.DAOImplementation.AuthorDaoPostgresql.insertAuthor(AuthorDaoPostgresql.java:136)
at projectRiferimentiBibliografici/com.ProjectRiferimentiBibliografici.Main.MainCe.main(MainCe.java:43)
The correct solution to this problem is to use a PreparedStatement - do not concatenate parameters into SQL strings.
Your problem with the date parameter is only the tip of the iceberg.
The next problem you'll get is, if Peter O'Donnel signs up.
So you should use something like this:
String authorName = "Paul";
String authorSurname = "Mac";
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse("2017-09-24", f);
String insert = "Insert into autore(nome_autore, cognome_autore, datanascita) values(?,?,?)";
PreparedStatement pstmt = connection.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, authorName);
pstmt.setString(2, authorSurname);
pstmt.setObject(3, date, java.sql.Types.DATE);
pstmt.executeUpdate();
There is a way to solve this. In the place Where is you specify the jdbc url.
Ex:
"jdbc:postgresql://host/schema"
Change above to
"jdbc:postgresql://host/schema?stringtype=unspecified"
Then your db determine type of your params not the jdbc driver.
Here you are using direct insert sql statement. As you are appending date object to string it will be converted to date.toString() which might not be expected format in sql.
Below is the insert sql statement:
"Insert into autore(nome_autore, cognome_autore, datanascita)
values('"+authorName+"', '"+authorSurname+"', '2017-09-24')")
Note: This approach of sql query building is not recommended and open to SQL Injection. Better to use PreparedStatement or an ORM framework.
I am trying to write a query and get results from oracle db using java and jdbc. My problem is the same query works if I try with statement, but the same query does not work if I use preparedStatement.
Statement Code: (Here I get real count value)
Statement stmt = con.createStatement();
String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate + "','YYYY-MM-DD')";
rs = stmt.executeQuery(sql);
PreparedStatement Code: (Here I get count value zero)
Date sqlDate = new java.sql.Date(someJava.Util.Date.getTime());// = 2015-09-24
sqlString = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE(?,'YYYY-MM-DD')";
pstmt = con.prepareStatement(sqlString);
pstmt.setDate(1, sqlDate);
rs = pstmt.executeQuery();
When I sysout my sqlDate prints like: 2015-09-24.
I have same problem with some other queries.
Can anyone know whats wrong here?
The TO_DATE function converts a string to a date given a certain format. So the parameter passed to the prepared statement should be the String to be converted by the Oracle function:
pstmt.setString(1, sqlDate.toString());
Or you can change the query so that the parameter is the date itself and pass the java.sql.Date object to the prepared statement:
sqlString = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = ?";
pstmt.setDate(1, sqlDate());
Note that, for the normal statement query:
String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate + "','YYYY-MM-DD')";
the String concatenation will append the string representation of the object, i.e. it is equivalent to:
String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate.toString() + "','YYYY-MM-DD')";
when i write database query :
select * from mytable WHERE subTitle='داتا باللغه العربيه';
it not return any thing but it is found in database table
Since you've included Java as a tag, I'll assume you're using JDBC for connecting to the database, in which case you should never be sending that particular string (SQL statement) to the database.
That is because that particular string implies string concatenation for building the SQL statement, as in:
String subtitle = "داتا باللغه العربيه";
String sql = "select * from mytable WHERE subTitle='" + subtitle + "'";
That is a very big no, no, because it leaves you vulnerable to SQL injection attacks.
Instead, you should be using a PreparedStatement and use parameters markers:
String subtitle = "داتا باللغه العربيه";
String sql = "select * from mytable WHERE subTitle=?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, subtitle);
try (ResultSet rs = stmt.executeQuery()) {
// use result set here
}
}
If this doesn't fix the character set issues you have, try using setNString instead. The 'N' is actually what you likely should have used for the string literal too, as in N'داتا باللغه العربيه', but don't use the string literal.
select * from mytable WHERE subTitle='داتا باللغه العربيه'
I'm searching on the web for several times but did not found anything which could help me (in java).
In fact I need to search in a sql table some rows from some reference which contains an hyphen. The issue made is that the sql replace my reference by the result of a substraction. The type of the columns are string.
Statement stmt = con.createStatement();
String query = "SELECT * FROM WAREHOUSE WHERE REF LIKE('96-18')" ;
Statement statement = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString("S_FAMILY"));
}
In this code, it replaces my reference by 78 and does not naturaly return the good result.
I've searched for an escape char but did not found.
Try sending the String as parameter on the query. Doing this requires to change the Statement into PreparedStatement:
String query = "SELECT * FROM WAREHOUSE WHERE REF LIKE(?)" ;
PreparedStatement pstatement = con.prepareStatement(query,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
pstatement.setString(1, "96-18");
ResultSet rs = pstatement.executeQuery();
Note: you should send "96-18" as value of a String variable, do not hard code it.
You can try
SELECT * FROM WAREHOUSE WHERE REF LIKE('96\-18') ESCAPE '\'
Hope it helps
How can I Convert Java Timestamp (Timestamp data type) to MySQL timestamp vice versa?
If you're using the JDBC API to access the database, and you're using a PreparedStatement to for example execute an SQL INSERT statement, then you just set the timestamp as a parameter to the PreparedStatement:
Timestamp ts = ...; // wherever you get this from
PreparedStatement ps = connection.prepareStatement("INSERT INTO MYTABLE (ts) VALUES (?)");
ps.setTimestamp(1, ts);
ps.executeUpdate();
Likewise, when you're doing a query that returns a timestamp, get it from the ResultSet by calling getTimestamp on it. Example:
Timestamp result = null;
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT ts FROM MYTABLE WHERE ...");
if (rs.next()) {
result = rs.getTimestamp(1);
}
See the JDBC Tutorial.
Without more specifics on the trouble you are having, this will be a hard question to answer. However, Java makes this relatively straightforward if you are using prepared statements. Your code would look something like this:
Connection conn = getConnection();
PreparedStatement pStmt = conn.prepareStatement("UPDATE my_table SET my_column = ? WHERE id = ?");
pStmt.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
pStmt.setInt(2, 42);
pStmt.executeUpdate();
As far as I can see from MySQL docs, java.sql.Timestamp should just work if you read it from or write it to a TIMESTAMP field in the database. So you should not need to do any conversion.