简体   繁体   中英

Equivalent C# of this PHP code

Trying to learn C# and I can't quite get a handle on querying and getting results. I'm trying to figure out both how to and the best way of doing the below in C# .NET. It's a MySql database.

//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);

This is my latest try: Also I realize I should probably be using parameters, but I just want it to work first

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();
}

The following WHERE clause:

WHERE accName =" + hashedAcc;

will cause an error if accName is not of type int , it needs quotes around it.

You should use parameterized query just like you did in PDO, it avoid errors like this and SQL injections as well.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM