![](/img/trans.png)
[英]Inserting a record in an SQL Server database using session in aspnet with C#
[英]Editing an sql database record using c#
我创建了一个连接到小型数据库的小型软件。 到目前为止,我正在使用c#和winfroms连接到本地sql服务器并在datagridview
显示数据库,我已经成功地将记录成功添加到数据库并选择了要编辑的记录。
因此,当我选择要编辑的记录并编辑所需字段时,我单击了“编辑”按钮,从理论上讲,该按钮应更新已编辑的记录。 但是,当我这样做时,似乎会遇到以下错误:(见图1)
图。1
我似乎无法弄清楚为什么我会发生此错误。 任何帮助将非常感激
接口:(图2)
图2
进行编辑btnEdit的代码:
private void btnEdit_Click(object sender, EventArgs e)
{
try
{
//Open Connection
sc.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM myEmployees WHERE EmpID" +
txtID.Text + " ", sc);
da.Fill(dt);
//start the editing of the selected record
dt.Rows[0].BeginEdit();
dt.Rows[0][1] = txtFName.Text;
dt.Rows[0][2] = txtLName.Text;
dt.Rows[0][3] = txtJRole.Text;
dt.Rows[0][4] = txtEmp.Text;
//dt.Rows[0][1] =
//stop editing
dt.Rows[0].EndEdit();
//sql commandbuilder that allow saving of records
SqlCommandBuilder cb = new SqlCommandBuilder(da);
//update the database
da.Update(dt);
//close connection
sc.Close();
loadEmp();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
// Application.ExitThread();
}
}
datagridview cick事件,它负责选择记录进行编辑:
private void dgEmployees_Click(object sender, EventArgs e)
{
try
{
DataTable dt = new DataTable();
SqlDataAdapter slctRow = new SqlDataAdapter("SELECT * FROM myEmployees WHERE EmpID=" +
Convert.ToInt16(dgEmployees.SelectedRows[0].Cells[0].Value.ToString()) + " ", sc);
slctRow.Fill(dt);
//display records into textboxes
txtID.Text = dt.Rows[0][0].ToString();
txtFName.Text = dt.Rows[0][1].ToString();
txtLName.Text = dt.Rows[0][2].ToString();
txtJRole.Text = dt.Rows[0][3].ToString();
txtEmp.Text = dt.Rows[0][4].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
// Application.ExitThread();
}
}
抛开参数化的问题-您错过了=
:
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM myEmployees WHERE EmpID="+
txtID.Text + " ", sc); // WARNING: SQL INJECTION RISK
然而; 我强烈建议您看一下参数化。 例如,如果我键入(在该文本框中)会发生什么:
0; delete from myEmployees --
尝试在btnEdit_Click
EmpID
之后添加=
:
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM myEmployees WHERE EmpID=" +
txtID.Text + " ", sc);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.