将Now()插入MYSQL

时间:2014-04-13 22:00:27

标签: html mysql jsp

我正在尝试从.jsp将当前日期和时间插入MYSQL,但我的代码无效。为什么?我没有时间设置为变量,因为我假设jsp将获取当前/日期,因为记录被加载到数据库中。我希望我已经足够解释了。

String insert1 = ("insert into ticket (t_date,t_equipment, t_descript,emp_id,tech_id)"
+ " values( now(),'"+a+"', '"+b+"', '"+c+"', '"+j+"')");

同样对于外键emp_id,我是否需要在insert语句中指定表名(employee.emp_id)或保留原样,因为我已经创建了emp_id数据库中的票证表中的FK?

表格代码:

CREATE TABLE IF NOT EXISTS `helpdesk`.`Ticket` (
  `T_ID` INT () NOT NULL AUTO_INCREMENT,
  `t_date` DATETIME NULL,
  `t_equipment` VARCHAR(45) NULL,
  `t_descript` VARCHAR(300) NULL,
  PRIMARY KEY (`T_ID`),
  CONSTRAINT `emp_id`
    FOREIGN KEY ()
    REFERENCES `helpdesk`.`employee` ()
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `tech_id`
    FOREIGN KEY ()
    REFERENCES `helpdesk`.`technician` ()
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

这是我得到的输出:

执行以下SQL语句:

insert into ticket (t_date,t_equipment, t_descript,emp_id,tech_id)
values(now(),'laptop', 'Can't access the network', '77777', '12344')
insert into employee (emp_id, emp_fname,emp_lname,emp_email, emp_phone,emp_cellphone,emp_dept)
values ('77777','Cassie','Somers','csomers@biz.org','2487775555','2487775551','null') 

哎呀,抛出了一个SQLException ..

.jsp代码:

String insert1 = ("insert into ticket (t_date,t_equipment, t_descript,emp_id,tech_id)" + 
"values(now(),'"+a+"', '"+b+"', '"+c+"', '"+j+"')");

String insert2 = ("insert into employee (emp_id, emp_fname,emp_lname,emp_email, emp_phone,emp_cellphone,emp_dept)" +
"values ('"+c+"','"+ d+"','"+e+"','"+f+"','"+g+"','"+h+"','"+i+"')");

1 个答案:

答案 0 :(得分:0)

根据您的错误消息&查询,t_date的数据库设置是DATETIME,但NOW()返回的格式与TIMESTAMP匹配。因此,您可以将CREATE TABLE更改为类似内容,因此默认t_date始终为TIMESTAMP DEFAULT CURRENT_TIMESTAMP

CREATE TABLE IF NOT EXISTS `helpdesk`.`Ticket` (
  `T_ID` INT () NOT NULL AUTO_INCREMENT,
  `t_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `t_equipment` VARCHAR(45) NULL,
  `t_descript` VARCHAR(300) NULL,
  PRIMARY KEY (`T_ID`),
  CONSTRAINT `emp_id`
    FOREIGN KEY ()
    REFERENCES `helpdesk`.`employee` ()
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `tech_id`
    FOREIGN KEY ()
    REFERENCES `helpdesk`.`technician` ()
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

然后您的查询可以完全放弃NOW()

String insert1 = ("insert into ticket (t_date,t_equipment, t_descript,emp_id,tech_id)"
+ " values('','"+a+"', '"+b+"', '"+c+"', '"+j+"')");

但是,这表示还有另一个主要问题:您显示的INSERT格式如下:

insert into ticket (t_date,t_equipment, t_descript,emp_id,tech_id)
values(now(),'laptop', 'Can't access the network', '77777', '12344')
insert into employee (emp_id, emp_fname,emp_lname,emp_email, emp_phone,emp_cellphone,emp_dept)
values ('77777','Cassie','Somers','csomers@biz.org','2487775555','2487775551','null')

但是单词Can't中有一个单引号('),它会关闭字符串值。因此,在处理它们之前,您应该在值mysqli_real_escape_string上使用Java等价物。抱歉,我不能提供有关Java的建议,但我更熟悉PHP,因此根据您提出的问题提供最好的建议。