c# - 您的 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);
}
}
}
}
如果有人可以帮助并修复此代码中的任何错误,我将非常感激。
解决方案
您的查询中缺少等号,很明显您会犯这种错误,因为您将字符串分解为几个部分,这将导致不可读。
这是一种更干净,更安全的方法
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)
推荐阅读
- jfreechart - JFreechart 中的多个堆叠区域数据集
- r - Shiny Plot Click Event - Updating Table Only
- google-chrome-devtools - How to send Chromium debugger a command (set breakpoint)?
- excel - VBA - 进程在我的计算机上正常运行,但不能在另一台计算机上运行
- html - 如何在 HTML 中将 CSD 文件渲染为 WAV
- python - How to add a 2nd Y-axis on a grouped bar chart using Altair? and sort the bar using value of one of the column from the data
- android-architecture-navigation - Android navigation component- With Login screens
- powershell - Get-ChildItem and wildcards and filtering
- python-3.x - Determine if number is prime example in python
- html - Border clipped off in Chrome but not IE or Edge