如何在 C# 中使用帶有動態參數的 INSERT INTO SQL 查詢? (How to use a INSERT INTO SQL Query with Dynamic parameters in C#?)


問題描述

如何在 C# 中使用帶有動態參數的 INSERT INTO SQL 查詢? (How to use a INSERT INTO SQL Query with Dynamic parameters in C#?)

Hello i have a method which saves some data in the SQL, but sometimes not every parameters are set, this gives me an exception becuase its NULL. 

Here is my Method:

 public string getBookingURL(string guid, BookingRequest request, string token, out string exitURL)
    {

        if (validateToken(token))
        {
            string command = "INSERT INTO OUTLOOKADDIN (GUID, TOKEN, BOOKINGID, STARTUTC, ENDUTC, SUBJECT, NUMPARTICIPANTS) VALUES (@GUID, @TOKEN, @BOOKINGID, @STARTUTC, @ENDUTC, @SUBJECT, @NUMPARTICIPANTS)";
            SqlConnection connection = new SqlConnection(GetConnectionString());
            connection.Open();
            try
            {
                SqlCommand cmd = new SqlCommand(command, connection);
                cmd.Parameters.Add("@GUID", guid);
                cmd.Parameters.Add("@TOKEN", token);
                cmd.Parameters.Add("@BOOKINGID", request.bookingID);
                cmd.Parameters.Add("@STARTUTC", request.startUTC);
                cmd.Parameters.Add("@ENDUTC", request.endUTC);
                cmd.Parameters.Add("@SUBJECT", request.subject);
                cmd.Parameters.Add("@NUMPARTICIPANTS", request.numParticipants);
                cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                cmd.Dispose();
                cmd = null;
            }

            catch (Exception ex)
            {
                log.Error(ex.Message + "\n\rStackTrace:\n\r" + ex.StackTrace);
            }
            finally
            {
                connection.Close();
            }

            HttpContext current = HttpContext.Current;
            string baseUrl = current.Request.Url.Scheme + "://"
                + current.Request.Url.Authority
                + current.Request.ApplicationPath.TrimEnd('/');

            exitURL = baseUrl + "/index.html";
            return baseUrl + '/'
                + "WebPage/Booking/BBooking.aspx?"
                + "OPS"
                + guid; ;

        }
        exitURL = null;
        return null;
    }

i think that this SQL Query...

  

string command = "INSERT INTO OUTLOOKADDIN (GUID, TOKEN, BOOKINGID,   STARTUTC, ENDUTC, SUBJECT, NUMPARTICIPANTS) VALUES (@GUID, @TOKEN,   @BOOKINGID, @STARTUTC, @ENDUTC, @SUBJECT, @NUMPARTICIPANTS)";

... should run dynamically or is there any other solution which prevents adding the parameter when its empty?

‑‑‑‑‑

參考解法

方法 1:

In addition to vignesh's post, use DBNull.Value for null values, if the DB fields are nullable.

EDIT: It is probably better to check the values BEFORE you even get to your getBookingURL() method. If you do proper validation before reaching this point then you can avoid the whole problem altogether.

if (/* date is null or not valid */)
    cmd.Parameters.Add("@mydate", SqlDbType.DateTime).Value = DBNull.Value;
else
    cmd.Parameters.Add("@mydate", SqlDbType.DateTime).Value = myDate;

方法 2:

You can add validation in the front end to prevent empty values

or 

you can check for null values before adding parameters

if(value!=null)
{
cmd.Parameters.Add("@GUID", guid);
} 
else
{
cmd.Parameters.Add("@GUID", "somestring or value");
} 

方法 3:

If your fields in the db table are unnulable, you must validate the values on the front end and show a warningto the user.

If the columns are nullable, you can send the DBNull to the database and it wont throw exception. My solution for it:

cmd.Parameters.AddWithValue("@ParameterName",
            (a == null) ? (object)DBNull.Value : a);

(by Eray GeveciPeet BritsVignesh SubramanianDoruk)

參考文件

  1. How to use a INSERT INTO SQL Query with Dynamic parameters in C#? (CC BY‑SA 3.0/4.0)

#visual-studio #SQL #C#






相關問題

如何在 C# 中使用帶有動態參數的 INSERT INTO SQL 查詢? (How to use a INSERT INTO SQL Query with Dynamic parameters in C#?)

擴展 SSRS 中的圖表功能 (Extending chart functionality in SSRS)

如何將 MVC 5 項目模板添加到 VS 2012? (How can I add the MVC 5 project template to VS 2012?)

Visual Studio - 將按鈕/複選框添加到工具欄以切換只讀文件屬性, (Visual Studio - Add a button/checkbox to a toolbar to switch the readonly file property,)

在 Javascript/Jquery Ajax 調用中使用 WCF 服務 (Consuming WCF service in Javascript/Jquery Ajax call)

Visual Basic 2013 - 控制台輸入令牌? (Visual Basic 2013 - Console Input Tokens?)

您是否知道用於編輯/翻譯資源(.rc)文件的好的程序? (Do you know of a good program for editing/translating resource (.rc) files?)

ADODB.Recordset 數據無法綁定到 datagridview (ADODB.Recordset data cannot bind into datagridview)

Reporting Services - 對數據源視圖 (DSV) 的報表模型 (SDML) 引用 (Reporting Services - Report Model (SDML) reference to Data Source View (DSV))

從 Visual Studio 2005 遷移到 2008 時要注意什麼? (What to look out for when moving from Visual Studio 2005 to 2008?)

動態改變另一個類的標籤值 (Dynamically changing the value of a label from another class)

在同一文件夾中為 .NET 5 和 .NET 6 Preview 3 構建 WebAssembly 項目 (Building WebAssembly project for both .NET 5 and .NET 6 Preview 3 in same folder)







留言討論