Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Insert null into SQL Compact Edition table

Iam trying to insert some data into a SQL Compact Edition table using parameter. My table allows null to be inserted but when I run my code below I can not get it working because one of these paramerters is going to be null sometimes and I would like to insert null into that column when the paramerter is null.

What how can I fix this?

string strConn = Properties.Settings.Default.SqlConnectionString;


        using (SqlCeConnection conn = new SqlCeConnection(strConn))
        {
            conn.Open();
            using (SqlCeCommand cmd = new SqlCeCommand("insert into table(ID, Name, Adress) values (@parm1, @parm2, @param3)", conn))
            {
                cmd.Parameters.AddWithValue("@parm1", ID);
                cmd.Parameters.AddWithValue("@parm2", Name);
                cmd.Parameters.AddWithValue("@parm3", Adress);

                cmd.ExecuteNonQuery();
            }
        }
like image 959
Alan_C Avatar asked Dec 13 '22 14:12

Alan_C


1 Answers

I think you can pass DBNull.Value as your value when it is null:

cmd.Parameters.AddWithValue("@parm2", (Name as object) ?? DBNull.Value);
like image 100
Stephen Chung Avatar answered Dec 28 '22 23:12

Stephen Chung