0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace ADO_DataSet_Prac
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DataSet ds = new DataSet();
        SqlDataAdapter da;
        DataTable dt;

        private void Form1_Load(object sender, EventArgs e)
        { 
            SqlConnection con = new SqlConnection("Server = localhost; Database = MSNETDB; Integrated Security=True;MultipleActiveResultSets=True");
             da = new SqlDataAdapter("Select * from Emp",con);
             da.Fill(ds, "Emp");
             dt=ds.Tables["Emp"];
             gvEmp.DataSource = dt;

           //Insert command for data adapter
            SqlCommand cmdInsert = new SqlCommand("Insert into Emp(EmpName,EmpSalary) Values(@Name,@Salary)", con);
            SqlParameter Name = cmdInsert.Parameters.Add("@Name", SqlDbType.VarChar, 100);
            SqlParameter Salary = cmdInsert.Parameters.Add("@Salary", SqlDbType.Money);
            Name.SourceColumn = "EmpName";
            Salary.SourceColumn = "EmpSalary";
            da.InsertCommand = cmdInsert;

            //Update command for data adapter
            SqlCommand cmdUpdate = new SqlCommand("Update Emp set EmpName =@Name, EmpSalary =@Salary where EmpId=@Id", con);
            SqlParameter Id = cmdUpdate.Parameters.Add("@Id", SqlDbType.Int);
            Name.SourceColumn = "EmpName";
            Salary.SourceColumn = "EmpSalary";
            Id.SourceColumn = "EmpId";
            da.UpdateCommand = cmdUpdate;
}
 private void btnDa_Update_Click(object sender, EventArgs e)
        {
            da.Update(ds,"Emp"); //Exception throw here
        }
    }
}

在尝试更新时,我得到一个SqlException说法:

必须声明标量变量“@Name”。

抛出异常

da.update(ds,"Emp") 

数据适配器的方法。我不知道是什么原因。我检查了所有语法和错误,一切看起来都很好,但仍然抛出错误。我也尝试过断点,但没有运气。

4

2 回答 2

2

您尚未在插入和更新命令中添加 sql 参数。

cmdUpdate.Parameters.Add(Name);
cmdUpdate.Parameters.Add(Salery);
于 2012-12-25T08:06:54.483 回答
2

您已为插入命令声明了参数 @Name 和 @Salary

cmdInsert.Parameters.Add("@Name"...

但后来您尝试将它们用于 updtae 命令。只需为更新添加新参数,例如:

SqlParameter NameUpdate = cmdUpdate.Parameters.Add("@Name", SqlDbType.VarChar, 100);
SqlParameter SalaryUpdate = cmdUpdate.Parameters.Add("@Salary", SqlDbType.Money);
于 2012-12-25T08:08:10.520 回答