C#SqlParameters速记 [英] C# SqlParameters Short Hand
本文介绍了C#SqlParameters速记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要带数据是录制的
对象,并把他们的内容到一个数据库列表
I'm taking data that is in a List
of Record
objects and putting their contents in to a database:
// Processes a Record and adds it to the database
public bool addRecord(SqlConnection db, List<Record> recordsToAdd)
{
using (SqlCommand command = db.CreateCommand())
{
foreach (Record record in recordsToAdd)
{
// Set the query command text
command.CommandText = @"INSERT INTO SMDGROUP_STPRODMASTER (PRODCODE, TOTFREE, TOTPHYS, ITEMTYPE, PRODESC) VALUES ('@PRODCODE', '@TOTFREE', '@TOTPHYS', '@ITEMTYPE', '@PRODESC')";
SqlParameter param1 = new SqlParameter("@CURSTAT", record.curstat);
SqlParameter param2 = new SqlParameter("@ITEMDESC", record.itemdesc);
SqlParameter param3 = new SqlParameter("@PRODCODE", record.prodcode);
SqlParameter param4 = new SqlParameter("@TOTFREE", record.totfree);
SqlParameter param5 = new SqlParameter("@TOTPHYS", record.totphys);
SqlParameter param6 = new SqlParameter("@ITEMTYPE", record.itemtype);
SqlParameter param7 = new SqlParameter("@PRODESC", record.proddesc);
command.Parameters.Add(param1);
command.Parameters.Add(param2);
command.Parameters.Add(param3);
command.Parameters.Add(param4);
command.Parameters.Add(param5);
command.Parameters.Add(param6);
command.Parameters.Add(param7);
// Execute the query
command.ExecuteNonQuery();
}
return true;
}
}
下面是我记录类:
class Record
{
public string curstat { get; set; }
public string itemtype { get; set; }
public string itemdesc { get; set; }
public string prodcode { get; set; }
public string proddesc { get; set; }
public string totfree { get; set; }
public string totphys { get; set; }
}
刚刚从看code,我有一种感觉,有实现这一目标的一个较短的方式。
Just from looking at the code, I've got a feeling that there is a shorter way of achieving this.
但其次,我甚至不知道我是否已经正确正在取代 @PARAMETER
值做到了。
But secondly, I'm not even sure if I've done it correctly that the @PARAMETER
values are being replaced.
如果我查看命令
的内容,它仍然显示查询字符串的 @
参数。
If I view the contents of command
, it still shows the query string with the @
parameters.
另外,我得到的 command.ExecuteNonQuery这个错误()
:
字符串或二进制数据将被截断。
String or binary data would be truncated.
语句已终止。
所以,我的问题是:
- 有一个较短的方式来设置和多个参数添加到查询?
- 什么引起的错误?
推荐答案
您有一个更大的构造函数:
You have a bigger constructor:
command.Parameters.Add(
"@CategoryName", SqlDbType.VarChar, 80).Value = "toasters";
这篇关于C#SqlParameters速记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文