使用参数查询

时间:2012-04-16 10:34:28

标签: c# mysql

我在Mysql中有一个查询,如下所示:

SELECT        id, nome, sigla
FROM            pais
WHERE    (estado=@estado)

在我不使用参数的代码中,我只会使用:

this.cidadeTableAdapter.Fill(this.anfeDataSet1.cidade); 

一切都会好的。

更多使用参数如何在参数上放置一个值并传递给TableAdapter?

2 个答案:

答案 0 :(得分:0)

using (SqlConnection connection = new SqlConnection(connectionString)) //create connection
{
        connection.Open();//openconnection

        using (SqlCommand command = new SqlCommand("SELECT id, nome, sigla FROM  pais
WHERE (estado=@estado)", connection)) //create command
        {

             command.Parameters.Add(new SqlParameter("estado", value)); //add parameter

             SqlDataReader reader = command.ExecuteReader(); //execute reader
             while (reader.Read())
             {
                 ...... //read the data
             }
        }
    }
}

答案 1 :(得分:0)

看看这个:http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx

SqlCommand com = new SqlCommand("SELECT id, nome, sigla FROM  pais WHERE (estado=@estado)", connection);
com.Parameters.Add(new SqlParameter("estado", value)); 
        SqlDataAdapter cidadeTableAdapter = new SqlDataAdapter();
        cidadeTableAdapter.SelectCommand = this.com;
        DataSet set = new DataSet("return");
        cidadeTableAdapter.Fill(set);
        this.com.Connection.Close();
        return set;

最佳选择btw是使用与数据库的连接,因此您不必显式关闭它。