[英]Equivalent C# of this PHP code
Trying to learn C# and I can't quite get a handle on querying and getting results. 尝试学习C#,我不太了解查询和获取结果的方法。 I'm trying to figure out both how to and the best way of doing the below in C# .NET.
我正在尝试找出在C#.NET中执行以下操作的方法和最佳方法。 It's a MySql database.
这是一个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);
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子句:
WHERE accName =" + hashedAcc;
will cause an error if accName
is not of type int
, it needs quotes around it. 如果
accName
的类型不是int
,将导致错误,它需要用引号引起来。
You should use parameterized query just like you did in PDO, it avoid errors like this and SQL injections as well. 您应该像在PDO中一样使用参数化查询,这样可以避免此类错误以及SQL注入。
var query = "SELECT userPass FROM 49Users WHERE accName = @hashedAcc";
var cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@hashedAcc", hashedAcc);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.