【发布时间】:2018-03-18 02:13:02
【问题描述】:
我正在学习SqlCommandbuilder,但是当我尝试实现它时,我遇到了一个异常。这是我的代码。
代码 sn-p #1:工作正常
protected void btnGetStudent_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlDataAdapter da = new SqlDataAdapter("Select * from tblStudents where ID = @Id", con);
da.SelectCommand.Parameters.AddWithValue("@Id", txtStudentID.Text);
DataSet ds = new DataSet();
da.Fill(ds, "Students"); // now this FILL is very useful as it manages opening of the connection and then executing the command to get the data and the loading it into the dataset and then closes the connection.
ViewState["SQL_Query"] = da.SelectCommand.ToString();
ViewState["Data"] = ds;
if (ds.Tables["Students"].Rows.Count > 0)
{
DataRow dr = ds.Tables["Students"].Rows[0];
txtStudentID.Text = dr["Id"].ToString();
}
}
代码 sn-p #2:导致异常:
protected void btnUpdate_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand =
new SqlCommand((string)ViewState["SQL_Query"], con);
SqlCommandBuilder builder = new SqlCommandBuilder(dataAdapter);
DataSet ds = (DataSet)ViewState["Data"];
DataRow dr = ds.Tables["Students"].Rows[0];
dr["Id"] = txtStudentID.Text;
int rowsUpdated = dataAdapter.Update(ds, "Students"); // Exception
}
例外:
“系统”附近的语法不正确
【问题讨论】:
-
反对的选民也请发表评论,以便我解决我的问题。您完全有权投反对票,但请花一些时间解释反对票。
-
由于我是初学者我不知道还需要什么其他细节,如果你问我,我会把我的整个项目解决方案放在这里。
-
想知道:实例化
builder有什么意义?我没有看到你在使用它 -
我只是跟着这个教程“youtube.com/…”
-
在工作版本中,您将
"Select * from tblStudents where ID = @Id"传递给 DataAdapter,在损坏的情况下,您将传递(string)ViewState["SQL_Query"]。(string)ViewState["SQL_Query"]的值是多少?
标签: c# .net sql-server ado.net