C# SqlParameters 简写 [英] C# SqlParameters Short Hand

查看:13
本文介绍了C# SqlParameters 简写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在获取 Record 对象的 List 中的数据并将它们的内容放入数据库:

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;
    }
}

这是我的 Record 类:

Here's my Record class:

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; }
}

仅通过查看代码,我就感觉到有一种更短的方法可以实现这一目标.

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.

如果我查看command的内容,它仍然显示带有@参数的查询字符串.

If I view the contents of command, it still shows the query string with the @ parameters.

此外,我在 command.ExecuteNonQuery() 上收到此错误:

Also, I'm getting this error on 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆