Oracle 时间操作
Java 对 Oracle 的时间类型的处理和对 MySQL的时间类型的处理是不同的,下面介绍了Java如何拼接sql语句,往Oracle数据库中插入时间类型的数据。
数据库表结构
CREATE TABLE STUDENT (
ID NUMBER(38) PRIMARY KEY,
NAME VARCHAR2(50),
SEX NUMBER(3),
CREATE_TIME DATE
);
Java拼接SQL
方式一
sysdate表示获取当前时间
int id = 1;
String name = "jack";
int sex = 25;
String sql1 = "INSERT INTO STUDENT " +
"(ID, " +
"NAME, " +
"SEX, " +
"CREATE_TIME) VALUES " +
"(" + id + ", " +
"'" + name + "', " +
sex + ", " +
"sysdate)";
// INSERT INTO STUDENT (ID, NAME, SEX, CREATE_TIME) VALUES (1, 'jack', 25, sysdate)
-- 插入数据库后
|ID |NAME |SEX |CREATE_TIME
|1 |jack |25 |2022-01-03 09:23:12
方式二
注意 下面的Date 为 java.sql.Date
int id = 1;
String name = "jack";
int sex = 25;
String sql2 = "INSERT INTO STUDENT " +
"(ID, " +
"NAME, " +
"SEX, " +
"CREATE_TIME) VALUES " +
"(" + id + ", " +
"'" + name + "', " +
sex +", " +
"to_date('"+new java.sql.Date(System.currentTimeMillis())+"', 'yyyy-mm-dd hh24:mi:ss'))";
// INSERT INTO STUDENT (ID, NAME, SEX, CREATE_TIME) VALUES (1, 'jack', 25, to_date('2022-01-03', 'yyyy-mm-dd hh24:mi:ss'))
-- 插入数据库后
|ID |NAME |SEX |CREATE_TIME
|1 |jack |25 |2022-01-03 00:00:00
方式三
注意下面的Date 为 java.util.Date
int id = 1;
String name = "jack";
int sex = 25;
String sql3 = "INSERT INTO STUDENT " +
"(ID, " +
"NAME, " +
"SEX, " +
"CREATE_TIME) VALUES " +
"(" + id + ", " +
"'" + name + "', " +
sex +", " +
"to_date('"+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date())+"', 'yyyy-mm-dd hh24:mi:ss'))";
// INSERT INTO STUDENT (ID, NAME, SEX, CREATE_TIME) VALUES (1, 'jack', 25, to_date('2022-01-03 09:23:12', 'yyyy-mm-dd hh24:mi:ss'))
-- 插入数据库后
|ID |NAME |SEX |CREATE_TIME
|1 |jack |25 |2022-01-03 09:23:12