是否可以同时使用SQL command
登录和update
?我的意思是登录完成后,我想更改logat in 1
。我是否必须使用if
创建一个新的OpenConnection()
?
public bool IsLogin(string user, string pass) {
string query = $"SELECT * from utiliz WHERE username='{user}' AND password='{GetSha1(pass)}'";
string query_update = $"UPDATE utiliz SET logat='{1}' WHERE username='{user}'";
try
{
if (OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
reader.Close();
conn.Close();
return true;
}
else
{
reader.Close();
conn.Close();
return false;
}
}
else {
conn.Close();
return false;
}
}
catch (Exception ex) {
conn.Close();
return false;
}
}
这里有一些重要点。您必须使用参数化查询来提高查询在数据库层的性能,并避免诸如sql injection
之类的问题。您也可以使用事务来保持数据完整性。
检查示例波纹管是否带有注释(我没有测试此代码,可能无法在您的环境中正常工作:]
public bool IsLogin(string user, string pass)
{
// prepare the queries with parameters with '@' and parameter name
const string query = "SELECT count(username) from utiliz WHERE username = @username AND password = @password";
const string query_update = "UPDATE utiliz SET logat = @logat WHERE username = @username";
// prepare the encrypted password
string encryptedPass = GetSha1(pass);
// use a result variable to use as the function result
bool result = false;
try
{
if (OpenConnection())
{
// start a transaction from the connection object
using (MySqlTransaction tran = conn.BeginTransaction())
{
try
{
int userFound = 0;
// prepare the MySqlCommand to use the query, connection and transaction.
using (MySqlCommand userCommand = new MySqlCommand(query, conn, tran))
{
userCommand.Parameters.AddWithValue("@username", user);
userCommand.Parameters.AddWithValue("@password", encryptedPass);
userFound = (int) userCommand.ExecuteScalar();
}
if (userFound > 0)
{
// prepare the MySqlCommand to use the query, connection and transaction to update data
using (MySqlCommand logatCommand = new MySqlCommand(query_update, conn, tran))
{
logatCommand.Parameters.AddWithValue("@logat", DateTime.Now);
logatCommand.Parameters.AddWithValue("@username", user);
logatCommand.ExecuteNonQuery();
}
}
// commit the transaction
tran.Commit();
result = true;
}
catch (Exception ex)
{
// perform some log with ex object.
tran.Rollback();
}
finally
{
conn.Close();
}
}
}
}
catch (Exception e)
{
// perform some log...
return false;
}
return result;
}
根据Felipe Oriani的建议(并证明),您应该使用参数化查询。
但是,我要指出的是,您可以使用单个update
查询来执行此操作。技巧是过滤用户名和密码上的更新查询:
UPDATE utiliz SET logat = @logat WHERE username = @username AND password = @password
您想使用方法ExecuteNonQuery
运行查询,该方法返回受影响的行数。
如果凭据有效,则ExecuteNonQuery
原因将选择相关记录,然后进行更新,并返回where
作为受影响的记录数。否则,没有记录被更新,并且该方法返回1
。