如何检查值是否已经存在于数据库与c#统一(错误的SQL语法)



我试图得到如果一个值已经存在于我的数据库注册,我已经到处搜索的答案,但我得到这个错误:

"你有一个错误在你的SQL语法;检查与您的MariaDB服务器版本对应的手册,以获得在附近使用的正确语法。

我不知道我做错了什么…

void Start()
{
linhaConn = "Server=localhost;" +
"Database=jogo;" +
"User ID=root;" +
"Password=;" +
"Pooling=false;" +
"CharSet=utf8";
ConnDatabase(linhaConn);
}
void ConnDatabase(string lConn)
{
conn = new MySqlConnection(lConn);
conn.Open();

print("Conectado"); 
}
public void InserirDB()
{   
ConnDatabase(linhaConn);
txtUser = InpUserCriar.text;
txtEmail = InpEmail.text;
command = new MySqlCommand("select * from jogador where ([email] = '" + txtEmail + "')", conn);
int UserExist = (int)command.ExecuteScalar();
if (UserExist > 0)
{
print("already exists");
}
else
{
print("doesnt exists");
}
conn.Close();

编辑我做到了!下面是代码:

ConnDatabase(linhaConn);
txtUser = InpUserCriar.text;
txtEmail = InpEmail.text;
string countDataEmail;
command = new MySqlCommand("select count(*) from jogador where email= '" + txtEmail+ "' ;", conn);
countDataEmail = command.ExecuteScalar().ToString();
if (countDataEmail == "0")
{
print("it doesnt exist");
}
else
{
print("email already exists");
}

如果你只是想检查他们是否查询返回一行,你可以使用UserExist。HasRows

我只是想提一下SQL注入! 无论何时处理用户输入,请确保它们不会损害或从数据库中检索某些内容。请参阅使用预处理语句来避免这种情况的示例。


除此之外,你确定它应该是

... where ([email] = some@email.address)

而不是(how I know SQL queries)

... where email = some@email.adddres;

所以组合起来可能是

command = new MySqlCommand("select * from jogador where email = @email;", conn);
command.Parameters.AddWithValue("@email", txtEmail);
commandPrepare();

最新更新