c# - 错误问题(当前名称在 中不存在)
问题描述
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 查询中遇到错误。请帮我解决一下这个。
解决方案
在没有看到实际错误的情况下很难确定,但我猜你的连接有问题。con
在 中定义btnSave_Click
但在 中不可访问BindData
。您需要将连接对象作为参数传递给该方法。或者更好的是,生成一个新的连接,因为传递连接对象可能会产生许多其他问题。
void BindData(SqlConnection con)
或者
void BindData()
{
SqlConnection con = //Generate connection here
...
}
*注意:正如上面评论中提到的,您的代码在其当前状态下极易受到 sql 注入攻击和其他安全问题的影响。绝对不要以纯文本形式存储数据库连接信息并参数化查询的所有输入。
推荐阅读
- php - php oop、pdo 和 ajax 实例问题
- javascript - 如何在 Vue js 中使 localStorage 中的数据具有反应性
- python - Python - 包不是相对于它们的当前目录吗?
- python - 如何让模板和 Python 在 Flask 中进行通信?
- markdown - PanDoc - 强制转换为 Markdown 以分别对 H1 和 H2 使用 # 和 ##
- android - 运行时错误:没有静态方法 checkSelfPermission
- svg - svg 填充 url 不适用于任何 Chrome 扩展页面,但适用于任何网站和本地文件
- swift - CAShapeLayer 没有收到触摸
- javascript - 需要折叠出搜索结果
- javascript - 返回一系列creationTimes中的最近时间