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))";
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");
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 (?, ?)";
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.
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.
I have this database table:
create table users(
id int not null auto_increment,
fn varchar(30),
ln varchar(30),
sex char,
email varchar(60),
country varchar(40),
username varchar(30),
password varchar(100),
primary key(id)
);
When I run this code, I am getting an error: Parameter index out of range (8 > number of parameters, which is 7). I also tried changing setString(1,fn) but it's not working.
try{
String INSERT="INSERT INTO users (fn,ln,,sex,email,country,username,password) VALUES (?,?,?,?,?,?,?)";
PreparedStatement pst=conn.prepareStatement(INSERT);
System.out.println("Created prepared statement");
pst.setString(2,"fn");
pst.setString(3,"ln");
pst.setString(4,"sex");
pst.setString(5,"email");
pst.setString(6,"country");
pst.setString(7,"username");
pst.setString(8,"password)");
pst.executeUpdate();
}
you have an extra comma in your query and your column count should start from 1.
String INSERT="INSERT INTO users (fn,ln,sex,email,country,username,password) VALUES (?,?,?,?,?,?,?)";
pst.setString(1,"fn");
pst.setString(2,"ln");
pst.setString(3,"sex");
pst.setString(4,"email");
pst.setString(5,"country");
pst.setString(6,"username");
pst.setString(7,"password)");
pst.executeUpdate();
You are passing 8 columns and 7 variables, count doesn't match.
Make sure if this:
String INSERT="INSERT INTO users (fn,ln,,sex,email,country,username,password) VALUES (?,?,?,?,?,?,?)";
should be like this:
String INSERT="INSERT INTO users (fn,ln,sex,email,country,username,password) VALUES (?,?,?,?,?,?,?)";
Parameter number relative to the query
pst.setString(1,"fn");
pst.setString(2,"ln");
pst.setString(3,"sex");
pst.setString(4,"email");
pst.setString(5,"country");
pst.setString(6,"username");
pst.setString(7,"password)");
pst.executeUpdate();
Corrections:
String INSERT="INSERT INTO users (fn,ln,sex,email,country,username,password) VALUES (?,?,?,?,?,?,?)";
and
short c = 0;
//using a counter variable (short or int) means
//no worries about numbering - just maintain the order below
pst.setString(++c,"fn");
pst.setString(++c,"ln");
pst.setString(++c,"sex");
pst.setString(++c,"email");
pst.setString(++c,"country");
pst.setString(++c,"username");
pst.setString(++c,"password)");
Note: ++c is pre-increment operator. It adds 1 to the current value of c (sets c to this) and uses the new value of c.