簡體   English   中英

通過ODBC傳遞null

[英]Pass null via ODBC

我在DB2中有一個存儲過程,它接受Date作為參數。 我用這段代碼在C#中為它賦值

cmd.Parameters.Add("myfield", OdbcType.DateTime).Value = MyDate;

這很好用! 但是有時我想把它傳遞給null,我無法讓它工作。 我試過了

cmd.Parameters.Add("myfield", OdbcType.DateTime);

cmd.Parameters.Add("myfield", OdbcType.DateTime).Value =DBNull.Value

更新

我的cmd.CommandText =“{CALL foo.MY_PROC_NAME(?)}”

當我運行它時它只返回沒有行。 SP中的MY SQL看起來像這樣

(p_myfield is null or LAST_UPDATE_DATE > p_myfield) 

像這樣的東西應該適用於可以為空的datetime參數

DateTime? myfield

if (null==myfield)
{
 var nullableparam = new OdbcParameter("@myfield", DBNull.Value);
 nullableparam.IsNullable = true;
 nullableparam.OdbcType = OdbcType.DateTime;
 nullableparam.Direction = ParameterDirection.Input;
 cm.Parameters.Add(nullableparam);
}
else
{
 cm.Parameters.AddwithValue("@myfield",myfield);
}

我沿着這些方面遇到了幾個錯誤:

  • 我無法將NULL值直接傳遞給Odbc
  • 命名參數似乎不起作用。

經過幾個小時的徹底解決問題后,我終於想到了我曾經在Java項目中看到過這種情況。 我改變了我的代碼只使用“?” 對於參數(就像我在Java代碼中所做的那樣),然后確保我按照我希望將它們添加到查詢的順序向OdbcCommand對象添加參數。 像魔法一樣,它起作用了。

這是一個例子:

OdbcTransaction lTransaction = MyConnection.BeginTransaction();
object[] my_params = function_to_get_input();
toInsert = new OdbcCommand();
toInsert.CommandText = string.Format("INSERT INTO table_name (`col1`,`col2`,`col3`) VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?);");
toInsert.Parameters.AddWithValue("val0", my_params[0]);
toInsert.Parameters.AddWithValue("val1", my_params[1]);
toInsert.Parameters.AddWithValue("val2", my_params[2]);
toInsert.Parameters.AddWithValue("val3", my_params[3]);
toInsert.Parameters.AddWithValue("val4", my_params[4]);
toInsert.Parameters.AddWithValue("val5", my_params[5]);
toInsert.Parameters.AddWithValue("val6", my_params[6]);
toInsert.Parameters.AddWithValue("val7", my_params[7]);
toInsert.Parameters.AddWithValue("val8", my_params[8]);
toInsert.Connection = MyConnection;
toInsert.Transaction = lTransaction;
toInsert.ExecuteNonQuery();
lTransaction.Commit();

可以重寫此方法,以便您可以選擇插入批量數據。 如果要插入批量數據,則必須限制使用一個INSERT語句插入的記錄數。 如果傳輸到服務器的數據量超過MAX_ALLOWED_PACKET值,則會生成錯誤。 請參閱此處了解更多詳情。

請原諒我的懶惰,沒有顯示正確的錯誤處理或其他任何事情。 我一直試圖弄清楚如何修復這個錯誤,現在進行了6個小時,並且即將瘋狂地捕獲“我不能使用命名參數,但我必須使用命名參數!”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM