这个PHP代码的等价C#

时间:2014-11-29 01:58:18

标签: c# php mysql

尝试学习C#,我无法完全了解查询和获得结果。我试图弄清楚如何以及在C#.NET中执行以下操作的最佳方法。这是一个MySql数据库。

//Interact with the DB. Find out if this hashed account #'s in there.
$dbh = $this->getPDO();
$procedure = "SELECT userPass FROM 499Users WHERE accName = :acc";
$call = $dbh->prepare($procedure);
$call->bindParam(':acc', $testAcc, PDO::PARAM_STR);
$call->execute();

//Fetch up to 1 result row
$row = $call->fetch(PDO::FETCH_ASSOC);

这是我最近的尝试:我也意识到我应该使用参数,但我只想让它先工作

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();

conn_string.Server = "*";
conn_string.UserID = "*";
conn_string.Password = "*";
conn_string.Database = "*";
conn_string.Port = 3306;

MySqlConnection connection = new MySqlConnection(conn_string.ToString());


try
{
    Console.WriteLine("Trying to connect to: ..." + conn_string); Console.WriteLine("Connecting to MySQL...");

    connection.Open();

}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}

string hashedAcc = this.HashPassword(acc);
//Verify hashed account
string query = "SELECT userPass FROM 49Users WHERE accName =" + hashedAcc;

MySqlCommand cmd = new MySqlCommand(query, connection);

MySqlDataReader myReader;
myReader = cmd.ExecuteReader();
try
{
    while (myReader.Read())
    {
        Console.WriteLine(myReader.GetString(0));
    }
}
finally
{
    myReader.Close();
    connection.Close();
}

1 个答案:

答案 0 :(得分:2)

以下WHERE子句:

WHERE accName =" + hashedAcc;
如果accName不是int类型,

会导致错误,它需要引用它。

您应该像在PDO中一样使用参数化查询,它可以避免像这样的错误和SQL注入。

var query = "SELECT userPass FROM 49Users WHERE accName = @hashedAcc";
var cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@hashedAcc", hashedAcc);