首页 > 解决方案 > 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册。在第 1 行的 "" 附近使用正确的语法

问题描述

我使用 C# 和 HelioHost MySQL 制作了一个登录页面。写了连接所需的所有内容,但仍然存在错误。试图自己修复它,但我决定到达这里。

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace TestLoginForm
{
    public partial class Form1 : Form
    {
        int i;
        MySqlConnection consql = new MySqlConnection(@"Data Source=tommy.heliohost.org;port=3306;Initial Catalog=mydatabase;uid=user;password='secretpass'");
        public Form1()
        {
            InitializeComponent();
        }

       

        private void button1_Click(object sender, EventArgs e)
        {
            i = 0;
            consql.Open();
            MySqlCommand cmd = consql.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from users where username ='"+usernameBox.Text+"'and password'"+passwordBox.Text+"'";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            da.Fill(dt);
            i = Convert.ToInt32(dt.Rows.Count.ToString());
            consql.Close();

            if (i == 0)
            {
                MessageBox.Show("You have entered invalid credentials", "Invalid credentials", MessageBoxButtons.OK, MessageBoxIcon.Error);
                usernameBox.Text = "";
                passwordBox.Text = "";
            }
            else
            {
                MessageBox.Show("Connection with database was successfully established and all input data matches the table contents", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
        }
    }
}

如果有人可以帮助并修复此代码中的任何错误,我将非常感激。

标签: c#mysqlformsauthentication

解决方案


您的查询中缺少等号,很明显您会犯这种错误,因为您将字符串分解为几个部分,这将导致不可读。

这是一种更干净,更安全的方法

MySqlCommand cmd = consql.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT * FROM users WHERE username = @uname AND password =@pass ";
            cmd.Parameters.AddWithValue("@uname",usernameBox.Text)
            cmd.Parameters.AddWithValue("@pass",passwordBox.Text)
            cmd.ExecuteNonQuery();

因此,通过这种方式,您可以在单个字符串中编写查询,并在要插入值的任何位置定义 @key。并像这样提供这个键的值:

        cmd.Parameters.AddWithValue("@key",value)

推荐阅读