[英]ado.net can't read from my database
This is a really noob-problem but im tearing my hair soon. 这确实是一个菜鸟问题,但我很快就把头发撕了。 I'm trying to read from my local database but it gives me nothing. 我正在尝试从本地数据库中读取内容,但没有任何帮助。 Here is the code: 这是代码:
protected void readBtn2_Click(object sender, EventArgs e)
{
string ConnString = "server=localhost; Trusted_Connection=yes; database=expreimentalDB";
string SqlString = ("SELECT * FROM tblCity WHERE city = '@city'");
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand cmd = new SqlCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("city", cityTB.Text);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
GridView1.DataSource = reader;
GridView1.DataBind();
}
}
}
}
The connectionstring should work (because if i rename the database part in the string it crashes). connectionstring应该可以工作(因为如果我在字符串中重命名数据库部分会导致崩溃)。
The sql is working (tried it in sql manager) sql正在工作(在sql管理器中尝试过)
reader (the SqlDataReader) is empty What is it I havnt tried out yet? reader(SqlDataReader)为空,我尝试过什么?
You need to remove the single quotes from around @city in your query so that it becomes 您需要删除查询中@city附近的单引号,以使其成为
string SqlString = "SELECT * FROM tblCity WHERE city = @city";
and then 接着
cmd.Parameters.AddWithValue("city", cityTB.Text);
needs to be changed to 需要更改为
cmd.Parameters.AddWithValue("@city", cityTB.Text);
I'm not quite sure, but shouldn't you have to prefix the name of the parameter with the @-sign when adding it to your command? 我不太确定,但是在将参数添加到命令中时,是否不必在参数名称前加上@符号? Like this: 像这样:
cmd.Parameters.AddWithValue("@city", cityTB.Text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.