zoukankan      html  css  js  c++  java
  • 使用SqlDataSource调用带参数存储过程插入数据

    最近被朋友问到一个SqlDataSource调用带参数存储过程为什么不成功,代码如下:

    代码
    string user_name = ((TextBox)this.DetailsView1.Rows[1].Cells[1].Controls[0]).Text.ToString().Trim();

    string pass_word = ((TextBox)this.DetailsView1.Rows[2].Cells[1].Controls[0]).Text.ToString().Trim();
    SqlDataSource1.InsertCommand
    = "pro_newUser";
    SqlDataSource1.InsertCommandType
    = SqlDataSourceCommandType.StoredProcedure;

    SqlDataSource1.InsertParameters.Add(
    "x", TypeCode.String, user_name);
    SqlDataSource1.InsertParameters.Add(
    "y", TypeCode.String, pass_word);

    SqlDataSource1.Insert()

            是啊,为什么不成功呢,提示的消息是太多的参数,这段代码看起来没什么问题啊。几轮搜索以后,觉得网上说的种种原因,最可能的是参数名要和字段名一致和参数要加@于是改成:

    string user_name = ((TextBox)this.DetailsView1.Rows[1].Cells[1].Controls[0]).Text.ToString().Trim();  
     
    string pass_word = ((TextBox)this.DetailsView1.Rows[2].Cells[1].Controls[0]).Text.ToString().Trim();  
    SqlDataSource1.InsertCommand = "pro_newUser";  
    SqlDataSource1.InsertCommandType = SqlDataSourceCommandType.StoredProcedure;  
     
    SqlDataSource1.InsertParameters.Add("@empNo", TypeCode.String, user_name);  
    SqlDataSource1.InsertParameters.Add("@empName", TypeCode.String, pass_word);  
     
    SqlDataSource1.Insert()

    存储过程里也进行相应的修改,把定义的传入参数和调用的地方都改为@empNo,@empName,仍然失败!错误消息变成了

    Procedure or Function 'asdfg' expects parameter '@empNo', which was not supplied.就是没找到@empNo,此时,我有点迷茫。

    于是把@去掉,再试,成功。代码如下:

    代码

    string user_name = ((TextBox)this.DetailsView1.Rows[1].Cells[1].Controls[0]).Text.ToString().Trim();

            string pass_word = ((TextBox)this.DetailsView1.Rows[2].Cells[1].Controls[0]).Text.ToString().Trim();
            SqlDataSource1.InsertCommand = "pro_newUser";
            SqlDataSource1.InsertCommandType = SqlDataSourceCommandType.StoredProcedure;

            SqlDataSource1.InsertParameters.Add("empNo", TypeCode.String, user_name);
            SqlDataSource1.InsertParameters.Add("empName", TypeCode.String, pass_word);

            SqlDataSource1.Insert()



    但是会产生两条数据,这段代码是写在DetailsView1_ItemInserting里的,根据以前的经验,这个方法在点DetailsView1的插入按钮时触发,只要InsertCommand中有代码,就会去执行,那么最后的一句SqlDataSource1.Insert()具有相同的作用,所以等于把insertCommand执行了两次,所以会有两条数据。

    很奇怪,我一直觉得我遇到的问题别人也一定会遇到过,但是这个例外,尝试了各种搜索条件,没有这个问题。所有的文章都说调用存储过程传参要用@占位符。

  • 相关阅读:
    UML中类图的符号解释
    Vim简明教程【CoolShell】
    C++ 指针—02 指针与引用的对照
    一个通用onReady函数的实现
    内存泄漏以及常见的解决方法
    个人博客之路
    WPF 设置WebBrowser控件不弹脚本错误提示框
    Solr使用入门指南
    用C语言写解释器(一)——我们的目标
    数据库索引的作用和长处缺点
  • 原文地址:https://www.cnblogs.com/Sabre/p/1755520.html
Copyright © 2011-2022 走看看