i got a table made in this way
CREATE TABLE WS_NAPACQ00T
( IDE_IDEN varchar2(20) PRIMARY KEY NOT NULL,
CLB_CXML CLOB,
SYS_DATE TIMESTAMP
);
and this java code to put in dt_date current date.
Timestamp dt_date = new Timestamp(System.currentTimeMillis());
String insertXML = "insert into WS_NAPACQ00T (IDE_IDEN, CLB_CXML, SYS_DATE) values ('10', 'test', '"+dt_date+"' ) ";
result = statement.executeQuery(insertXML);
the error is:
"not a valid month"
how can i resolve?
Don't use Statement it can lead to SQLInjection, instead use PreparedStatement as follows.
String insertXML = "insert into WS_NAPACQ00T (IDE_IDEN, CLB_CXML, SYS_DATE) values (?, ?, ?) ";
PreparedStatement statement = connection.prepareStatement(insertXML);
statement.setString(1,"10");
statement.setString(2,"test");
statement.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
result = statement.executeQuery();
Unrelated.
If you want to insert current timestamp you can use CURRENT_TIMESTAMP. SELECT CURRENT_TIMESTAMP from DUAL; will give the current timestamp.
Related
I am trying to insert some rows using a prepare-bind statement. One of the columns is of type TIMESTAMP. How do I bind the variable for this column with the current epoch time?
I have the following table:
CREATE TABLE orders {
user_id TEXT,
order_time TIMESTAMP,
order_id UUID DEFAULT gen_random_uuid(),
order_details TEXT,
PRIMARY KEY (user_id, order_time DESC, order_id),
FOREIGN KEY (user_id) REFERENCES %s (user_id)
);
I have the following prepare statement code:
String stmt = "INSERT INTO orders " +
"(user_id, order_time, order_details) " +
"VALUES (?, ?, ?);"
PreparedStatement p = connection.prepareStatement(stmt);
Now I am trying to bind the current epoch time System.currentTimeMillis() to variable 2 in this statement. How should I do that?
The corresponding Java type to your SQL's TIMESTAMP is most likely java.sql.Timestamp. You can generate a current timestamp using:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
So, your prepared statement code might look like:
String stmt = "INSERT INTO orders " +
"(user_id, order_time, order_details) " +
"VALUES (?, ?, ?);"
PreparedStatement p = connection.prepareStatement(stmt);
p.setString(1, "Karthik");
p.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
p.setString(3, "here is some order text");
I have an insert query where along with other fields , I am inserting Timestamp. Now whenever, value of Timestamp is null, I am getting the error -
java.sql.SQLException: ORA-00932: inconsistent datatypes: expected DATE got BINARY
I am using oracle 11g.
Query is :
#Modifying
#Query(value ="INSERT INTO mams_asset a ( a.mams_asset_id, a.mams_folder_id, a.asset_name, a.gist, a.last_modified_date, a.last_exported_date, a.created_date ) VALUES (hextoraw(?1), hextoraw(?2), ?3, ?4, ?5, ?6 , ?7)" , nativeQuery = true)
int insertIntoMamsAsset(String mamsAssetId, String mamsFolderId, String assetName, String gist, Timestamp lastModifiedDate, Timestamp lastExportedDate, Timestamp createdDate);
This is though spring data JPA one. I tried using this approach too but same error:
public int insertIntoMamsAsset(String mamsAssetId, String mamsFolderId, String assetName, String gist, Timestamp lastModifiedDate, Timestamp lastExportedDate, Timestamp createdDate){
final Query query = entityManager.createNativeQuery("INSERT INTO mams_asset a ( a.mams_asset_id, a.mams_folder_id, a.asset_name, a.gist, a.last_modified_date, a.last_exported_date, a.created_date ) VALUES (hextoraw(?), hextoraw(?), ?, ?, ?, ? , ?)")
.setParameter(1, mamsAssetId)
.setParameter(2,mamsFolderId)
.setParameter(3,assetName)
.setParameter(4,gist)
.setParameter(5,lastModifiedDate)
.setParameter(6,lastExportedDate)
.setParameter(7,createdDate);
return query.executeUpdate();
}
Though the query seems long but you can focus only on Timestamp field that's what is generating error.
What is the work around for this ?
This worked for me
final Query query = entityManager.createNativeQuery("INSERT INTO mams_asset a ( a.mams_asset_id, a.mams_folder_id, a.asset_name, a.gist, a.last_modified_date, " +
"a.last_exported_date, a.created_date ) VALUES (hextoraw(?), hextoraw(?), ?, ?, ?, ? , ?)")
.setParameter(1, mamsAssetId)
.setParameter(2, mamsFolderId)
.setParameter(3, assetName)
.setParameter(4, gist)
.setParameter(5, lastModifiedDate, TemporalType.TIMESTAMP)
.setParameter(6, lastExportedDate, TemporalType.TIMESTAMP)
.setParameter(7, createdDate, TemporalType.TIMESTAMP);
I added TemporalType.TIMESTAMP in setParameter.
It happens cause your table dont admit null value for last_modified_date.
Try to check if the input value lastModifiedDate is null or no before launche the query like this
if(lastModifiedDate = null){
Timestamp myModifiedDate = new Timestamp(0001-01-01 00:00:00);
}
Or simply change the database like this:
ALTER TABLE table_name MODIFY COLUMN date TIMESTAMP NULL
This oracle message is happens when you try to insert a value to a column from different types for more detail :
http://www.dba-oracle.com/sf_ora_00932_inconsistent_datatypes_expected_string_got_string.htm
now to insert a date value better to use Calendar class or Date class.
Could someone tell me what I'm doing wrong here? I have a table like this:
mysql> describe mytable;
Field Type Null Key Default Extra
-----------+----------+--------+--------+------------+---------------
id int(11) NO PRI NULL auto_increment
foreignid int(11) NO MUL NULL
date date NO '0000-00-00'
[some more columns]
I'm trying to insert values via a preparedStatement:
String insert = "insert into mytable (foreignid, date) values (?, ?)";
PreparedStatement pst = connection.prepareStatement(insert);
pst.setInt(1, newForeignID); //valid foreign key
pst.setDate(2, newDate); //newDate is a proper java.sql.Date
pst.execute();
That should be fairly straightforward, yet I always get this error:
Unknown column 'date' in 'field list'
Any idea why that happens?
date is a Keyword in mysql. You should escape or better rename it:
String insert = "insert into mytable (foreignid, `date`) values (?, ?)";
public static void createLoan(Loan loan){
Connection con = null;
try {
con = JDBCConnectionFactory.getInstance().getNewConnection();
String sql = "";
sql = "INSERT INTO loan (users_id, book_id, loan_date, loan_dueDate) "
+ "VALUES (?, ?, CURDATE(), DATE_ADD(CURDATE(),INTERVAL 30))";
PreparedStatement prep = con.prepareStatement(sql);
prep.setLong(1, loan.user.getDatabaseId());
prep.setLong(2, loan.book.getDatabaseId());
Why can´t I use the DATE_ADD function to set a specific date? It just returns Null.
DATEADD Method example :
SELECT OrderId,DATEADD(day,45,OrderDate) AS OrderPayDate
FROM Orders
check this one : http://www.w3schools.com/sql/func_dateadd.asp
function Date_Add has signature DATE_ADD(date,INTERVAL expr unit) you are missing the unit.
I tried with below sample data
CREATE TABLE `person` (
`ID` INT(11) NOT NULL,
`NAME` VARCHAR(100) NOT NULL,
`loanduedate` DATETIME DEFAULT NULL
) ;
INSERT INTO person VALUES(4,'shirish',DATE_ADD(CURDATE() , INTERVAL 45 DAY));
and the insert went fine.
table has below data inserted successfully
ID NAME loanduedate
------ ------- -------------------
4 shirish 2015-06-11 00:00:00
Source
DATE_ADD(date,INTERVAL expr unit)
The date argument specifies the starting date or datetime value.
expr is an expression specifying the interval value to be added or subtracted from the starting date. expr is a string; it may start with a “-” for negative intervals.
unit is a keyword indicating the units in which the expression should be interpreted.
And for you, the problem is that unit is missing you should select it from the table of unit value, like DAY.
sql = "INSERT INTO loan (users_id, book_id, loan_date, loan_dueDate) "
+ "VALUES (?, ?, CURDATE(), DATE_ADD(CURDATE(),INTERVAL 30 DAY))";
I'm having troubles to insert into a TIMESTAMP field correctly.
The method looks like this:
private static void addPickup(Connection conn, boolean debug, String
logfileName, String serverName, String mapName, long start,
long end) throws SQLException {
try (CallableStatement statement = conn.prepareCall("{CALL AddPickup "
+ "(?, ?, ?, ?, ?) }")) {
statement.setString(1, logfileName);
statement.setString(2, serverName);
statement.setString(3, mapName);
statement.setTimestamp(4, new Timestamp(start));
statement.setTimestamp(5, new Timestamp(end));
statement.execute();
}
}
start has the value 1373573918000
end has the value 1373574819000
Procedure:
CREATE PROCEDURE AddPickup(
IN logfilename VARCHAR(45),
IN servername VARCHAR(10),
IN mapname VARCHAR(20),
IN start TIMESTAMP,
IN end TIMESTAMP
)
AddPickup:BEGIN
IF EXISTS(SELECT p.id FROM pickup p WHERE p.logfile_name = logfilename) THEN
LEAVE AddPickup;
END IF;
INSERT IGNORE INTO map (name) VALUES (mapname);
INSERT IGNORE INTO server (name) VALUES (servername);
INSERT INTO pickup (logfile_name, server_id, map_id, started, ended, datetime)
VALUES (
logfilename,
(SELECT s.id FROM server s WHERE s.name = servername),
(SELECT m.id FROM map m WHERE m.name = mapname),
start,
end,
NOW()
);
END //
Tables:
CREATE TABLE map (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20) UNIQUE NOT NULL
) ENGINE = 'InnoDB';
CREATE TABLE server (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(10) UNIQUE NOT NULL
) ENGINE = 'InnoDB';
CREATE TABLE pickup (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
logfile_name VARCHAR(45) UNIQUE NOT NULL,
server_id INT UNSIGNED NOT NULL,
map_id INT UNSIGNED NOT NULL,
started TIMESTAMP NOT NULL,
ended TIMESTAMP NOT NULL,
datetime DATETIME NOT NULL,
FOREIGN KEY (map_id) REFERENCES map(id) ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (server_id) REFERENCES server(id) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE = 'InnoDB';
It inserts everything into the table as it should, just the both TIMESTAMP fields, pickup.started and pickup.ended always show "0000-00-00 00:00:00" and I can't figure out why.
I think the problem is in the argument you pass to setTimestamp
When I use the setTimestamp, if i haven't specific date to use, I've always pass a new Date().getTime() as argument.
private static void addPickup(Connection conn, boolean debug, String
logfileName, String serverName, String mapName, long start,
long end) throws SQLException {
try (CallableStatement statement = conn.prepareCall("{CALL AddPickup "
+ "(?, ?, ?, ?, ?) }")) {
statement.setString(1, logfileName);
statement.setString(2, serverName);
statement.setString(3, mapName);
statement.setTimestamp(4, new Date().getTime());
statement.setTimestamp(5, new Date().getTime());
statement.execute();
}
}
I am not pretty sure about the thing how it works in the MYSQL but when i was working with the timestamp in SQLSERVER,the TIMESTAMP used to generate automatically whenever the row was created,in that case i was not providing any value for timestamp from the query. So just try n insert other values
Hope it might help you also.