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")
数据适配器的方法。我不知道是什么原因。我检查了所有的语法和错误,一切看起来很好,但仍然是抛出错误。我也尝试过断点,但没有运气。
答案 0 :(得分:2)
您尚未在插入和更新命令中添加sql参数。
cmdUpdate.Parameters.Add(Name);
cmdUpdate.Parameters.Add(Salery);
答案 1 :(得分:2)
您已通过
为insert命令声明参数@Name和@SalarycmdInsert.Parameters.Add("@Name"...
但是后来你试图将它们用于updtae命令。只需为更新添加新参数,例如:
SqlParameter NameUpdate = cmdUpdate.Parameters.Add("@Name", SqlDbType.VarChar, 100);
SqlParameter SalaryUpdate = cmdUpdate.Parameters.Add("@Salary", SqlDbType.Money);