【问题标题】:How to build a dynamic Command and Parameter method to insert a record into SQL如何构建动态命令和参数方法以将记录插入 SQL
【发布时间】:2017-10-01 17:17:25
【问题描述】:

我需要作为 DATA TABLE 插入 SQL(所有新记录) 我的问题是数据表可能有许多不同的列,从 2 到 15。 我已经能够动态地构建命令文本(插入 xxx(col1,col2)值(@col1,@col2)”没有问题。 我还能够创建一个字符串 myparamstring = command.paramerter["@col1"].value = "val1"; command.paramerter["@col2"].value = "val2";

但我突然意识到,我实际上会执行 command.executeNonQuery())

【问题讨论】:

  • 发布您的代码。
  • 你试过使用“command.executeNonQuery()”吗???这个问题缺少一个好问题的所有重要部分......主要是其他人有机会提供帮助所需的细节。

标签: c# sql sql-server command sql-insert


【解决方案1】:

在您对所做工作的介绍中存在一些问题。参数不是字符串,它们是 SqlParamaters,可以明确定义SqlParameter p1 = new SqlParameter("@col1", "val1"); 或直接添加到命令对象cmd.Parameters.AddWithValue("@col1", "val1"); 查询的实际执行实际上是你所拥有的。 command.executeNonQuery() 方法的一个共同点是它返回一个整数,反映受影响的行数。对于插入,它应该是 1,但如果您要删除多条记录,它会更高或限制(通过 WHERE)它可能是 0。我在 catch 语句中分配负数以便于识别问题。

无论如何,这是我将如何编写要通过 ADO 在 SQL Sever 上运行的语句的粗略布局:

int RowsAffected;
using (SqlConnection conn = new SqlConnection(strConn)) {

    string cmdText = "insert into xxx(col1, col2) values(@col1,@col2)";

    using (SqlCommand cmd = new SqlCommand(cmdText, conn)) {

        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@col1", "val1");
        cmd.Parameters.AddWithValue("@col2", "val2");

        try {
            conn.Open();
            RowsAffected = cmd.ExecuteNonQuery();
        }
        catch (SqlException sx) {
            RowsAffected = -1;
            Console.Write(sx); // your SQL error handling
        }
        catch (Exception ex) {
            RowsAffected = -2;
            Console.Write(ex); // other exception handling
        }
        finally {
                // your cleanup routines
                conn.Close();
                Console.Write("Rows Added = " + RowsAffected);
            }
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2018-07-21
    相关资源
    最近更新 更多