我的整个删除方法()被成功执行,并且没有错误,但当调试器应用查询线的记录不被删除
问题描述:
表示textBox1.Text.my代码没有数据被以下:我的整个删除方法()被成功执行,并且没有错误,但当调试器应用查询线的记录不被删除
namespace SeparateConnection
{
class clsGridView
{
Connection co2 = new Connection();
//display our global varaible for connection
SqlConnection myconn3 = new SqlConnection("data source=M-SULEMAN-PC;initial catalog=dbmsLogin;integrated security=sspi");
public void Delete()
{
co2.setconn();
try
{
DialogResult result = MessageBox.Show("Are you sure you want to delete ?", "Message",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
//myconn3.Open();
DataTable table2 = new DataTable();
frmGridView gd = new frmGridView();
SqlDataAdapter myadd2 = new SqlDataAdapter("Delete from tblLogin where UserName ='" + gd.textBox1.Text + "'", myconn3);
myadd2.Fill(table2);
//Sqlcommandbulider to allow changes to database
SqlCommandBuilder mybuild = new SqlCommandBuilder(myadd2);
//Update the database
myadd2.Update(table2);
//Close the connection
myconn3.Close();
}
else
return;
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
----------当我使用相同的类调用和定义method..there是没有问题的
答
要删除数据,必须遵循这个模式:
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Delete from tblLogin where UserName = @param";
cmd.Parameters.Add("@param", gd.textBox1.Text);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
答
为什么不试试这样的东西
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
sql = "delete product where Product_name ='Product6'";
try
{
connection.Open();
adapter.DeleteCommand = connection.CreateCommand();
adapter.DeleteCommand.CommandText = sql;
adapter.DeleteCommand.ExecuteNonQuery();
MessageBox.Show ("Row(s) deleted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
我以为你应该使用ExecuteScalar进行删除,插入和更新操作,它会返回受影响的行数? – SimpleVar 2012-04-19 07:50:53
请注意该代码中的sql注入漏洞 – Hari 2012-04-19 07:59:47
构造函数是:'public SqlDataAdapter(string selectCommandText,...)' - 它不适用于DELETE语句。我很惊讶没有例外。 – 2012-04-19 08:24:07