如何将参数值添加到语句中

时间:2019-05-06 15:43:09

标签: c# sql sqlcommand

我正在努力弄清楚为什么我在@database变量中遇到了必须声明的错误。

我基本上尝试了所有方法,但都无济于事。

    public static Person ReturnItem(Person person)
    {
        if(person.ID == null)
        {
            person.Name = "Error, null return Item";
            return person;
        }

        try{
            SqlConnection connect = RetaloDB.GetConnection();
            SqlCommand selectCommand = Return_Sql_Select_String("Person.dbo", person.ID.ToString(), "PerID", connect);
            Person person2 = PersonOperations.ReturnPerson(selectCommand, connect);
            return person2;
        }
        catch(Exception ex){
            throw ex;
        }
    }

  public static SqlCommand Return_Sql_Select_String(string database, string id, string idname, SqlConnection connect){

        string selectStatement
            = "Select *"
            + "FROM @database " 
            + "Where @idname = @id";
        SqlCommand selectCommand = new SqlCommand(selectStatement, connect);

        selectCommand.Parameters.AddWithValue("@database", database);
        selectCommand.Parameters.AddWithValue("@id", id);
        selectCommand.Parameters.AddWithValue("@idname", idname);
        return selectCommand;

    }

public static Person ReturnPerson(SqlCommand selectCommand, SqlConnection connect)
    {

        Person person = new Person();
        try
        {

            connect.Open();
            SqlDataReader personReader = selectCommand.ExecuteReader(CommandBehavior.SingleRow);

我只想从数据库中获取一些数据。但是我得到了必须声明表变量@database的信息。而且我不知道我在做什么错。

0 个答案:

没有答案