简体   繁体   English

如何使用 c# 检查值是否已存在于数据库中以实现统一(SQL 语法错误)

[英]How to check if value already exists in database with c# for unity (error in SQL syntax)

I'm trying to get if a value already exists in my database for a registration and I've searched everywhere for an answer but I get this error:我正在尝试获取我的数据库中是否已经存在用于注册的值,并且我到处搜索答案,但出现此错误:

" You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near...at line 1". “您的 SQL 语法有错误;请查看与您的 MariaDB 服务器版本相对应的手册,以获取在第 1 行附近使用的正确语法”。

I don't know what I'm doing wrong...我不知道我做错了什么...

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

EDIT I did it: Here is the code:编辑我做到了:这是代码:

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

If you just want to check if they query returns ant row you can use UserExist.HasRows如果您只想检查他们查询是否返回 ant 行,您可以使用 UserExist.HasRows

I just wanted to mention SQL Injection .我只想提一下SQL Injection Whenever dealing with User Input make sure they can't harm or retrieve something from your database.每当处理用户输入时,请确保他们不会损害或从您的数据库中检索某些内容。 See the example which uses a prepared statement to avoid that.请参阅使用准备好的语句来避免这种情况的示例


besides that, are you sure it should be除此之外,你确定它应该是

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

instead of (how I know SQL queries)而不是(我怎么知道 SQL 查询)

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

So together it would probably be something like所以在一起可能会像

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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