我已经在论坛上看了一遍并尝试了人们建议的所有内容,但我找不到能够使这个解决方案有效的解决方案。程序将一直运行,直到它必须连接到数据库。然后在那时它将出现以下错误:
类型' System.Data.SqlClient.SqlException'未处理的异常发生在System.Data.dll
中其他信息:' user'附近的语法不正确。
User
是我的登录页面中的用户名。
这是我的代码。任何人都可以看到我遗失的任何问题吗?
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 System.Data.SqlClient;
namespace LoginForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source= (LocalDB)\v11.0;AttachDbFilename=C:\Users\Username\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From Login where Username'" +textBox1.Text + "' and Password ='"+textBox2.Text+"'",con);
DataTable dt = new DataTable();
sda.Fill(dt);
if(dt.Rows[0][0].ToString() == "1")
{
this.Hide();
Main ss = new Main();
ss.Show();
}
else
{
MessageBox.Show("please check Username and Password and try again.");
}
}
}
答案 0 :(得分:1)
更好地使用真实SqlParameter
。但首先这应该有所帮助:
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From Login where Username ='" +textBox1.Text + "' and Password ='"+textBox2.Text+"'",con);
但是你的程序非常不安全,因为你可能会遇到sql-injection个问题。
请查看SqlAdapter和SqlParameter:Getting SqlDataAdapter and SqlCommand confused
答案 1 :(得分:0)
其他人说这个代码是sql-injection
您不需要数据表来获取一个值
SqlConnection con = new SqlConnection(@"Data Source (LocalDB)\v11.0;AttachDbFilename=C:\Users\Spyer\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "Select Count(*) From Login where Username = '" + textBox1.Text + "' and Password = '" + textBox2.Text + "'";
con.Open();
Int32 ccount = (Int32)cmd.ExecuteScalar();
con.Close();
这是一种正确的方法
String connString = @"Data Source (LocalDB)\v11.0;AttachDbFilename=C:\Users\Spyer\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30");
String sql = "Select Count(*) From Login where Username = @Name and Password = @Password";
Int32 ccount;
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@Name", SqlDbType.VarChar);
cmd.Parameters["@Name"].Value = textBox1.Text;
cmd.Parameters.Add("@Password", SqlDbType.VarChar);
cmd.Parameters["@Password"].Value = textBox2.Text;
try
{
conn.Open();
ccount = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}