sql查询问题(不接收参数)

时间:2015-05-28 10:54:14

标签: c# sql asp.net visual-studio-2012

我在c#中有以下代码用于sql insert:

using (DM dbManager = new DM())
{
    dbManager.Command.CommandText = @"Insert into TransactionLog(TransactionNumber,Amount
    ,studentID) Values (@trnumber,@amount,@studentID) ; SELECT SCOPE_IDENTITY() ;";
    dbManager.Command.Parameters.AddWithValue("@trnumber", txnref);
    dbManager.Command.Parameters.AddWithValue("@amount", amount);
    dbManager.Command.Parameters.AddWithValue("@studentID", 
                                           Membership.GetUser().ProviderUserKey.ToString());

    id = Convert.ToInt32(dbManager.Command.ExecuteScalar());
}

但是不明白我为什么会收到这个错误:

 System.Data.SqlClient.SqlException: The parameterized query '(@trnumber 
 nvarchar(4000),@amount nvarchar(5),@studentID nvarcha' expects the 
 parameter '@trnumber', which was not supplied.

因为参数显然在查询中我尝试更改参数名称相同的问题。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

if (String.IsNullOrEmpty(txnref))
            {
                command.Parameters.AddWithValue("@trnumber", DBNull.Value); 
            }
            else
                command.Parameters.AddWithValue("@trnumber", txnref);

答案 1 :(得分:0)

如果值为空,请尝试放置ContentResolver cr = getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if (cur.getCount() > 0) { while (cur.moveToNext()) { String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID)); String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 它将起作用!还要检查您的列是否接受NULL