如何使用MySqlParameter有条件地将列设置为其默认值?

时间:2021-04-08 21:09:09

I have a table in a MySql database that stores user accounts. One of the columns, expires, stores an expiration date but defaults to NULL. I need to be able to remove an expiration date and set it back to the default value.

我在MySql数据库中有一个存储用户帐户的表。其中一列过期,存储过期日期,但默认为NULL。我需要能够删除过期日期并将其设置回默认值。

Currently, all of my CRUD routines are written using MySqlCommand with parameters. Can this be done directly with a MySqlParameter, or do I have to create an alternate command object to handle this eventuality?

目前,我的所有CRUD例程都是使用带参数的MySqlCommand编写的。这可以直接用MySqlParameter完成,还是我必须创建一个备用命令对象来处理这种可能性?

3 个解决方案

#1


3  

The problem was DBNull, doing:

问题是DBNull,做:

command.Parameters.AddWithValue("@parameter", null);

compiles OK.

#2


0  

It's not clear what conditions you're talking about. If you want to set column to default value, you can use DbNull.Value;

目前尚不清楚你在说什么条件。如果要将列设置为默认值,可以使用DbNull.Value;

command.AddWithValue("@param", DbNull.Value);

or

command.Parameters.Add("@param", <data type>).Value = DBNull.Value;

#3


0  

I usually set values that are intended to be default/blank to null in code, then before executing the query, run the following loop:

我通常在代码中将默认/空白的值设置为null,然后在执行查询之前运行以下循环:

foreach(MySqlParameter param in cmd.Parameters)
    if (param.Value == null) param.Value = DBNull.Value;

#1


3  

The problem was DBNull, doing:

问题是DBNull,做:

command.Parameters.AddWithValue("@parameter", null);

compiles OK.

#2


0  

It's not clear what conditions you're talking about. If you want to set column to default value, you can use DbNull.Value;

目前尚不清楚你在说什么条件。如果要将列设置为默认值,可以使用DbNull.Value;

command.AddWithValue("@param", DbNull.Value);

or

command.Parameters.Add("@param", <data type>).Value = DBNull.Value;

#3


0  

I usually set values that are intended to be default/blank to null in code, then before executing the query, run the following loop:

我通常在代码中将默认/空白的值设置为null,然后在执行查询之前运行以下循环:

foreach(MySqlParameter param in cmd.Parameters)
    if (param.Value == null) param.Value = DBNull.Value;