首页 > 解决方案 > 错误问题(当前名称在 中不存在)

问题描述

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 查询中遇到错误。请帮我解决一下这个。

标签: c#sql-servercrudvoid-pointerssqlcommand

解决方案


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

void BindData(SqlConnection con)或者

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

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


推荐阅读