[英]How to pass a MySQL database function as a query parameter from c#
Let me explain a little. 让我解释一下。
Image you have the flowing MySQL table: 图像中有流动的MySQL表:
CREATE TABLE test (
value DATETIME
);
Currently I am doing something like this: 目前我正在做这样的事情:
command.CommandText = "UPDATE test SET value = ?value";
command.Parameters.AddWithValue("?value", DateTime.Now);
But the clients date/time settings are unreliable so I would like the time to be determined at the server. 但是客户端的日期/时间设置不可靠,因此我希望在服务器上确定时间。 Something like:
就像是:
command.CommandText = "UPDATE test SET value = NOW()";
The trick is that I want to pass the "NOW()" function as a parameter to the original query. 诀窍是我想将“ NOW()”函数作为参数传递给原始查询。 Please understand that this small example is OVERLY simplified.
请理解,这个小例子已经过分简化。 In reality the table has 48 columns, 7 of which are datetime, marking the date and/or time the user made a particular operation to the object the database row denotes.
实际上,该表具有48列,其中7列是日期时间,标记用户对数据库行所表示的对象执行特定操作的日期和/或时间。 When the user performs a new operation to the object I read the entire row and insert it again, with a different ID of course, (Something like a poor man's revision history) so I like to keep the date/time of the old operation and insert it in the new row, but at the same time set the current date/time (as seen by the database) for the new operation.
当用户对对象执行新操作时,我会读取整行并以不同的ID再次插入它(当然,这类似于穷人的修订历史记录),因此我希望保留旧操作的日期/时间,将其插入新行,但同时设置新操作的当前日期/时间(如数据库所示)。
For simplicity lets go back to the previous example. 为简单起见,让我们回到上一个示例。
As far as I can find I have two choices. 据我所知,我有两个选择。
bool switch;
....
command.CommandText = "UPDATE test SET value = " + switch ? "NOW()" : "?value";
command.Parameters.AddWithValue("?value", value);
OR 要么
bool switch;
....
if (switch) {
command.CommandText = "SELECT NOW()";
value = Convert.ToDateTime(command.ExecuteScalar());
}
command.CommandText = "UPDATE test SET value = ?value";
command.Parameters.AddWithValue("?value", value);
I don't like neater of them. 我不喜欢整齐。 Wouldn't it be neat if I could do something similar to:
如果我可以做类似的事情不是很好吗?
command.CommandText = "UPDATE test SET value = ?value";
if (switch) {
command.Parameters.AddWithValue("?value", "NOW()");
} else {
command.Parameters.AddWithValue("?value", value);
}
That way I would still execute the same one query. 这样,我仍然会执行相同的一个查询。
Waiting for your opinions on this. 等待您对此的意见。 I will be very grateful for any help you can provide.
我将非常感谢您能提供的任何帮助。
You could use a stored procedure with an optional parameter to achieve this. 您可以使用带有可选参数的存储过程来实现此目的。 If the parameter is NULL, you use NOW() instead.
如果参数为NULL,则改为使用NOW()。 Although I'm not a big fan of stored procs (they are evil ! :-).
尽管我不是存储过程的忠实拥护者(它们是邪恶的!:-)。
You could also use IFNULL() . 您也可以使用IFNULL() 。 Here is how it is done in T-SQL (function name is ISNULL) :
这是在T-SQL(函数名称为ISNULL)中完成的方法:
UPDATE test SET value = ISNULL(@value, GetDate() )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.