I want to insert "0001-01-01" as a value into a date field by using Java PreparedStatement.
But it throws exception when I tried this:
String sql = "insert into mytable values(?)"
ps = conn.prepareStatement(sql);
ps.setDate(1, java.sql.Date.valueOf("0001-01-01"));
ps.executeUpdate(); // throws exceptions here.
The error is :
The supplied value is not a valid instance of data type datetime. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision.
If I don't use PreparedStatement, I can insert "0001-01-01". However,
prepare statement seems not allow me to insert this value.
It will work if I inserted "1969-01-01" instead of "0001-01-01".
Any ideas?
Updates:
Here are more info that might be needed.
we use sql server 2012.
we have to use "0001-01-01" because these values were already there. I am changing some very very old codes to use prepare statement. So I have to insert the same values in the same functionality.
Updates 2:
We are using "date" datatype, not "datetime" datatype.
Based on this https://msdn.microsoft.com/en-us/library/bb630352.aspx, "0001-01-01" is not out of range for "date" field.
In addition, I am able to insert "0001-01-01" to the date field without using prepare statement. i.e.
String sql = "insert into mytable values('0001-01-01')"
java.sql.Statement statement = conn.createStatement();
statement.executeUpdate(sql);
So it is not sql server's problem or db field's problem.
Try using the different suitable JDBC driver.
I've searched stackoverflow but did not found the solution (at least the way I want it).
I have a JSP page which calls a Java method to insert a date into Oracle database.
It passes a String.
The problem, how to build the string to execute the insert?
String myInsert = "INSERT INTO table_name
values (..., to_date(<<Java variable name>>, 'yyyy/mm/dd hh:mm'), ....);
where Java variable name refers to a variable of type String.
I want to let Oracle to the job, not necessarily using SimpleDateFormat, if it's possible. So, should I use '' or " "
Youre help would be very much appreciated
You should use a PreparedStatement along with its setDate function and not deal with date to string conversions yourself.
See http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#setDate(int,%20java.sql.Date)
String myInsert="INSERT INTO table_name values(...?)";
PreparedStatement ps=connection.prepareStatement(myInsert);
ps.setDate(1,<<java variable name>>);
...
I am using java's ResultSetMetaData.getColumnTypeName() method to find the resultset datatype of the dynamically constructed query. But for the below query
Select Adddate('2013-12-10',10) // MySQL Query
It return "Char". Why it so?? I expect Date.
Experts please help.
Thanks
You can try to cast your result to DATE:
SELECT CAST(ADDDATE('2013-12-10',10) as DATE);
I think ADDDATE behaves just like DATE_ADD, which returns string in this case:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
I'm trying to build a web page to better learn Java and SQL. My question is, is there a way in Java to make a generic SQL select statement? For example:
SELECT var1 FROM var2 WHERE var3=var4
or something of the sort.
My idea is to fill the vars with user selected items from the web page. I know this can be done in PHP using the Post method, but I'm not using PHP. Also, I've read about the Prepared Statement in Java, but seems only to work when the used after the comparison operator; ex:
SELECT * FROM table Where attr = ? &
Also, I do know i can do the hard coded version of "SELECT " + var1 + "FROM " + var2 + "WHERE attr = " + var3 + " " but that doesn't seem very generic and prone to a lot of errors.
Incase: I'm trying to build this test page using HTML & JSP.
What you are doing with the ? is parameterizing the query. The query can only be parameterized for values not names of tables or columns.
Every time you run a query. The database has to create a query plan. If you are running the same query again and again, you can reduce this overhead by creating a PreparedStatement.
The first execution of PreparedStatement will generate the query plan. The subsequent executions will reuse the same plan.
Same query here means, it is identical in all respects except values used in where clause, expressions etc.
If you change the Column or Table name or modify the structure of the query, then it is a different query and will require a different query plan. A PreparedStement is not useful in this case and you should stick to the hardcoded version you talked about. Because of this reason you will get an error if you try to parameterize Table or Column names in PreparedStement.
Having said that. It is not advisable to take such a generic approach for queries. If your queries are that simple, you can benefit from ORM tools. You would not have to maintain even a line of SQL. For complex queries you have an option of using ORM specific query language or JPQL or Native SQL. Look for JPA + Hibernate
Your specific usage is not permitted by JDBC. You need to hard code the table name when creating the prepared statement. If you really do want to do that I suggest you use String concatenation to create the SQL statements and then create a PreparedStatement with parameters to handle the where part. In case you are wondering why bother with PreparedStatements in the specific solution, it's to avoid SQL injection.
You can use PreparedStatement to achive your objective.
For example -
String query = "SELECT * FROM table Where attr = ?";
PreparedStatement pt = con.prepareStatement(query);
pt.setString(1, attribete);
pt.executeUpdate();
There is no such direct provision in any of SQL packaged classes or others to replace table, column names along with query parameter values, in a query string, using a single method.
You require to depend on both PreparedStatement and any of String methods replace(...) and replaceFirst(...) to achieve your requirement.
String sql = "Select $1, $2 from $3 where $4=? and $5=?";
sql = sql.replaceFirst( "$1", "col1_name" );
sql = sql.replaceFirst( "$2", "col2_name" );
sql = sql.replaceFirst( "$3", "table_name" );
sql = sql.replaceFirst( "$4", "col4_name" );
sql = sql.replaceFirst( "$5", "col5_name" );
// .. and so on
PreparedStatement pst = con.prepareStatement( sql );
// use relevant set methods to set the query parametrs.
pst.setXXX( 1, value_for_first_query_parameter ); // from a variable or literal
pst.setXXX( 2, value_for_second_query_parameter); // from a variable or literal
// ... and so on
If you are using JDBC, can try this
PreparedStatement statement = connection.prepareStatement("SELECT ? FROM ? WHERE ?=? ");
then
statement.setString(1, "column_name");
statement.setString(2, "table_name");
statement.setString(3, "column_name");
statement.setBigDecimal(4, 123);
If you are using other ORM like Hibernate or JPA, I believe there are also ways to do.
Are there any patterns or known ways of converting a date from a string representation to a numerical representation and vice versa?
Background:
I am using an Apache Derby database as the persistence for a Java program. I would like to do something like this:
Select * from MyTable where date_column > 20100914154503 order by date_column DESC
// 20100914154503 = 2010-09-14 15:45:03
My dates are stored in my java program I am using Joda Time ( https://www.joda.org/joda-time/) DateTime object.
Thanks
I'm not too sure what you're actually trying to do or why you need to use a string at all, but in general you should use a PreparedStatement. Then you can just set the date in the PreparedStatement using a java.sql.Timestamp:
DateTime date = ...;
Connection conn = ...;
PreparedStatement ps = conn.prepareStatement(
"Select * from MyTable where date_column > ? order by date_column DESC");
ps.setTimestamp(1, new Timestamp(date.getMillis()));
Strongly consider looking into how your database manages dates and time, since it can probably do what you need. Remember that the date you have should be stored in a date field in the database table.