简体   繁体   English

MySQL C#插入查询服务器时间戳

[英]MySQL C# Insert query Server timestamp

I have a C# program and I want to run a MySQL query that insert a record. 我有一个C#程序,我想运行一个插入记录的MySQL查询。 In this record I have a timestamp field that MUST BE the server timestamp, not the client timestamp. 在此记录中,我有一个时间戳字段,该字段必须是服务器时间戳,而不是客户端时间戳。 So, I write this: 所以,我这样写:

start_session = new MySqlDataAdapter("INSERT INTO CUBE_WORKTIME(ID_WORKTIME,
                                      ID_RISORSA_FK,DATA,ORA_INIZIO_EVENTO, ORA_FINE_EVENTO,
                                      ID_CDC_FK, CAUSALE, LAST_EVENT)
                             VALUES ('', '"+ idrisorsa_global + "', DATE(NOW()),NOW(),
                                     NULL, '"+ IDCDC +"', 'Login', 'Y')", connection);

DataTable start_session_dataset = new DataTable();
start_session.Fill(start_session_dataset);

This query works well, the ID_RISORSA_FK and IDCDC fields are correct. 此查询工作良好, ID_RISORSA_FKIDCDC字段正确。 But the date and the datetime are 0000-00-00 and 0000-00-00 00:00:00. 但是日期和日期时间是注册和注册00:00:00。 I also tried adding the quotes, but no effects. 我也尝试添加引号,但没有效果。

Any ideas? 有任何想法吗?

The first thing to change is the use of an MySqlDataAdapter to just insert a record. 要做的第一件事是使用MySqlDataAdapter仅插入一条记录。 While this could work it is not the correct class to use for this work. 尽管这可以工作,但不是用于此工作的正确类。 A simple MySqlCommand is the correct object to use and with a lot less of infrastructure required 一个简单的MySqlCommand是要使用的正确对象,所需的基础结构要少得多

The second thing to change is the way in which you build your sql query. 更改的第二件事是构建sql查询的方式。 Do not concatenate together strings to form an sql command but use Parameters. 不要将字符串连接在一起以形成sql命令,而要使用Parameters。 This avoid Sql Injection and parsing problems. 这样可以避免Sql注入和解析问题。

So your code could be rewritten as 因此您的代码可以重写为

string cmdText = @"INSERT INTO CUBE_WORKTIME 
         (ID_RISORSA_FK,DATA,ORA_INIZIO_EVENTO, ORA_FINE_EVENTO,ID_CDC_FK, 
          CAUSALE, LAST_EVENT) VALUES (@risorsaID, CURDATE(), CURTIME(),
          NULL, @cdcID, 'Login', 'Y')";

MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.Parameters.Add("@risorsaID", MySqlDbType.Int32).Value = idrisorsa_global;
cmd.Parameters.Add("@cdcID", MySqlDbType.Int32).Value = IDCDC;
int rowsInserted = cmd.ExecuteNonQuery();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM