我尝试使用MySQL数据库在C#中创建登录表单,但是我收到此错误: “字段列表”中的未知列“计数” 。我该怎么办?
有错误的图片:
这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ScoalaIT
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string myConnection = "server=localhost;database=test;uid=root;password=123456";
MySqlConnection connection = new MySqlConnection(myConnection);
//string StrQuery1 = "Select count from users where user='" + txtUser.Text + "' and parola='" + txtParola.Text + "'";
MySqlCommand myCommand = new MySqlCommand("Select count from users where user='" + txtUser.Text + "' and parola='" + txtParola.Text + "'", connection);
//MySqlDataAdapter MyAdapter = new MySqlDataAdapter(myCommand);
MySqlDataReader myReader;
connection.Open();
myReader = myCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count++;
}
if (count == 1)
{
MessageBox.Show("Ok");
}
else
{
MessageBox.Show("Nu ok");
}
connection.Close();
}
}
}
感谢!!!
答案 0 :(得分:4)
改变这个......
"Select count from
到此......
"Select count(*) from
然后阅读此内容:http://en.wikipedia.org/wiki/SQL_injection因为您确定会受此影响。
答案 1 :(得分:1)
问题: count
是保留字
解决方案:你可以将后面的刻度内的重复单词包装起来。
试试这个:
MySqlCommand myCommand = new MySqlCommand("Select `count` from users where
user='" + txtUser.Text + "' and parola='" + txtParola.Text + "'", connection);
建议:您的查询对sql注入攻击开放我建议使用参数化查询来避免它们。
注意:如果您想获得匹配用户的总数,那么您应该使用count(*)
代替count
试试这个:
MySqlCommand myCommand = new MySqlCommand("Select count(*) from users where
user='" + txtUser.Text + "' and parola='" + txtParola.Text + "'", connection);
使用参数化查询:完整解决方案
MySqlCommand myCommand = new MySqlCommand("Select count(*) from users where
user=@username and parola=@password", connection);
myCommand.Parameters.AddWithValue("@username",txtUser.Text);
myCommand.Parameters.AddWithValue("@pasword",txtParola.Text);
int totalCount = Convert.ToInt32(myCommand.ExecuteScalar());
if (totalCount > 0)
{
MessageBox.Show("Ok");
}
else
{
MessageBox.Show("Nu ok");
}
答案 2 :(得分:0)
count
是一个MySQL函数。这意味着您不应该为列命名。但如果你这样做,你必须将它包装在刻度线中:
MySqlCommand myCommand = new MySqlCommand("Select `count` from users where user='" + txtUser.Text + "' and parola='" + txtParola.Text + "'", connection);
如果您尝试获取WHERE
caluse匹配的行数,则需要计算一些内容才能实现:
MySqlCommand myCommand = new MySqlCommand("Select count(*) from users where user='" + txtUser.Text + "' and parola='" + txtParola.Text + "'", connection);