【问题标题】:error problem(the current name doesn't exist in the ) [closed]错误问题(当前名称不存在)[关闭]
【发布时间】:2021-04-07 12:58:17
【问题描述】:
private void btnSave_Click(object sender, EventArgs e)
{
           
    SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=LoginDB;Integrated Security=True");
    con.Open();
    SqlCommand commamd = new SqlCommand("insert into tblUser values ('"+string.Format(txtUser.Text)+"' , '"+ txtServer.Text+"' , '"+txtpwd.Text+"', getdate())" ,con );
    commamd.ExecuteNonQuery();
    MessageBox.Show("Successfully Inserted");
    con.Close();
    BindData();
}

void BindData() 
{
    SqlCommand command = new SqlCommand("select * from tblUser" ,con);
    SqlDataAdapter sd = new SqlDataAdapter();
    DataTable dt = new DataTable();
    sd.Fill(dt);
    dataGridView.DataSource = dt;
}

我在新的 sqlcommand 查询中遇到错误。请帮我解决这个问题。

【问题讨论】:

  • 它不会解决您的问题,但这是 sql 注入的完美候选者。您需要参数化您的数据。
  • 也是纯文本密码的完美候选者。而且对于重新排序的列也很脆弱。并且也不保证SqlCommand、SqlConnection 和SqlDataAdapter 的处置。启动时,显示一个连接仍然打开的 MessageBox
  • 请发布完整的异常消息,它发生在哪一行?
  • 也属于“插入后从数据库进行完全刷新”的反模式

标签: c# sql-server crud void-pointers sqlcommand


【解决方案1】:

如果没有看到实际错误,很难确定,但我猜你的连接有问题。 conbtnSave_Click 中定义,但在 BindData 中不可访问。您需要将连接对象作为参数传递给该方法。或者更好的是,生成一个新的连接,因为传递连接对象可能会产生许多其他问题。

void BindData(SqlConnection con)

void BindData()
{
    SqlConnection con = //Generate connection here
    ...
}

*注意:如上面的 cmets 所述,您的代码在其当前状态下极易受到 sql 注入攻击和其他安全问题的影响。绝对不要以纯文本形式存储数据库连接信息并参数化查询的所有输入。

【讨论】:

  • 是的,连接“con”的问题。
  • @ZeeshanIsmail 如果此答案对您有所帮助,请花点时间将其标记为解决方案 :) 谢谢!
猜你喜欢
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
相关资源
最近更新 更多