SQL Server数据库中的对象名称无效?

时间:2015-05-13 05:29:22

标签: c# asp.net sql-server

我收到此错误:

  

无效的对象名称'会员'

在这一行:

int MemberExist = (int)check_Member.ExecuteScalar();

使用我当前的DB,如下所示:http://imgur.com/6fyKGn3为什么不执行此操作?

代码:

// Get the connection 
SqlConnection DBConnection = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=""E:\DS\Prac5\Part1\App_Data\MyDatabase.mdf"";Integrated Security=True");

SqlDataReader Reader = null;

DBConnection.Open();
SqlCommand check_Member = new SqlCommand("SELECT * FROM Members WHERE MembershipID = FirstName AND LastName = @Txtnput", DBConnection);
check_Member.Parameters.AddWithValue("@Txtnput", txtMembershipid.Text);

int MemberExist = (int)check_Member.ExecuteScalar();

4 个答案:

答案 0 :(得分:1)

您的连接字符串中似乎有一些错误。

Data Source=(LocalDb)\v11.0;Initial Catalog=Database;Integrated Security=SSPI;AttachDBFilename='E:\DS\Prac5\Part1\App_Data\MyDatabase.mdf'

您也可以使用

"SELECT TOP 1 MembershipID  FROM Members WHERE MembershipID = FirstName AND LastName = @Txtnput"

确保您的表名是成员。您可以在模型或数据库中检查它。

bool IsMemberExist;
object MembershipId = check_Member.ExecuteScalar();

if(MembershipId  != null )
 {
   IsMemberExist = true;
  //Do other things here.  //Convert.ToInt32(MembershipId) 
 }

答案 1 :(得分:1)

请确保数据库MyDatabase.mdf是否包含名为Members的表。 请测试以下。

SqlCommand check_table= "select case when exists((select * from information_schema.tables where table_name = '" + tableName + "')) then 1 else 0 end");
int IsTableExists = (int)check_table.ExecuteScalar();
if(IsTableExists ==1)
{
        SqlCommand check_Member = new SqlCommand("SELECT * FROM Members WHERE MembershipID = FirstName AND LastName = @Txtnput", DBConnection);
        check_Member.Parameters.AddWithValue("@Txtnput", txtMembershipid.Text);
        int MemberExist = (int)check_Member.ExecuteScalar();
}

更新: 可以请用模式名称和表名更新查询。

例如:SqlCommand check_Member = new SqlCommand("SELECT * FROM dbo.Members WHERE MembershipID = FirstName AND LastName = @Txtnput", DBConnection);

更具体地说是MyDatabase.dbo.Members

答案 2 :(得分:0)

看起来您必须将查询更改为

"SELECT count(*) FROM Members WHERE MembershipID = FirstName AND LastName = @Txtnput"

因为ExecutesScalar需要从查询返回单个值。

答案 3 :(得分:0)

尝试此连接字符串并检查

    SqlConnection DBConnection = new SqlConnection(@"Data Source=(LocalDB)\v11.0;
AttachDbFilename=E:\DS\Prac5\Part1\App_Data\Database.mdf;Integrated Security=True")

删除“之间没有必要,因为以@开头也将MyDatabase.mdf更改为Database.mdf,因为在图片中它是Database.mdf