我无法执行标量查询。 " ="" ="" =" &#34 ;.问题是我想从表中访问性别,然后在数据读取器的帮助下更新另一个表。
SqlConnection con1 = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Muneeb\Documents\Visual Studio 2012\Projects\Dwh_Class_Project\Dwh_Class_Project\Centralised_db.mdf;Integrated Security=True");
string gender_get; // get the gender from the database
SqlCommand cmdgen = new SqlCommand();
cmdgen.CommandText = "select top 1 gender from name_lookupwhere name= 'ahmed'";
con1.Open();
cmdgen.Connection = con1;
string g = ((string) cmdgen.ExecuteScalar());
MessageBox.Show("test" + g);
答案 0 :(得分:2)
您缺少空格:name_lookupwhere
应为name_lookup where
。
另外,请注意您正在执行返回行的 select top 1 ...
,但使用ExecuteScalar
运行查询,该查询需要返回单个值。
答案 1 :(得分:0)
查询中缺少空格。 尝试:
cmdgen.CommandText = "select top 1 gender from name_lookup where name = 'ahmed'";
答案 2 :(得分:0)
应该这样做:
using(SqlConnection con1= new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Muneeb\Documents\Visual Studio 2012\Projects\Dwh_Class_Project\Dwh_Class_Project\Centralised_db.mdf;Integrated Security=True"))
{
using(SqlCommand cmdgen = new SqlCommand("select top 1 gender from name_lookup where name= @name", con1))
{
cmdgen.AddWithValue("@name", "ahmed");
string g = ((string) cmdgen.ExecuteScalar());
MessageBox.Show("test" + g);
}
}