VS 2015中代码出现错误

A error appeared in the code in VS 2015

我似乎对 VS 2015 有疑问。

它让我得到同样的错误,我不知道为什么。我在代码下面插入了。

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 System.Data.SqlClient;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
    public Form1()
    {
        InitializeComponent();
        textBox2.PasswordChar = '*';
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void Exit_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void LogIn_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Gigabyte\Desktop\apps\WindowsFormsApplication3\WindowsFormsApplication3\Database1.mdf;Integrated Security=True");
        con.Open();
        SqlDataAdapter sda = new SqlDataAdapter("SELECT Status FROM Login1 WHERE Username'" + textBox1.Text + "'AND Parola='" + textBox2.Text + "' ", con);
        con.Close();
        DataTable dt = new System.Data.DataTable();
        sda.Fill(dt);
        if(dt.Rows.Count==1)
        {
            Form2 ss = new Form2();
            ss.Show();
        }
    }
}
}

申请表停在 sda.Fill(dt); 行并显示此错误:

Blockquote An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll Blockquote Additional information: Incorrect syntax near 'aa'.

任何帮助都很棒!提前致谢!

编辑: 问题已解决!

我想你的字符串应该是这样的:

Status FROM Login1 WHERE Username ='" + textBox1.Text + "' AND Parola='" + textBox2.Text + "'

您可能漏掉了多余的空格 ;)

SqlDataAdapter sda = new SqlDataAdapter("SELECT Status FROM Login1 WHERE Username'" + textBox1.Text + "'AND Parola='" + textBox2.Text + "' ", con);

将此行更改为

SqlDataAdapter sda = new SqlDataAdapter("SELECT Status FROM Login1 WHERE Username='" + textBox1.Text + "'AND Parola='" + textBox2.Text + "' ", con);

您忘记了 = 符号。

您的 sql 中缺少 = 标志。

此外,您应该使用 SqlParameter 来清理数据库输入,而不是连接字符串。如果您继续实施,您正在为 SQL 注入做好准备。

另一项优化是 SqlDataAdapter 自动管理您的 SqlConnection,因此您在使用 [=17= 时无需调用 Open()Close() ]

var cmd = new SqlCommand();
cmd.CommandText = "SELECT Status FROM Login1 WHERE Username = @username AND Parola= @parola";
cmd.Parameters.AddWithValue("@username", textbox1.Text);
cmd.Parameters.AddWithValue("@parola", textbox2.Text);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);