gpt4 book ai didi

SQL Server 东西的 C# 代码错误

转载 作者:行者123 更新时间:2023-11-30 20:44:12 24 4
gpt4 key购买 nike

我在我的应用程序上使用 Access 数据库并切换到 SQL Server,但它无法正常工作...这是一个登录屏幕,连接按钮单击事件。

当我连接时,它会跳过并关闭包含我输入的任何信息的登录窗口。

这是我遇到的错误。cmd 栏是红色的,不知道为什么。

http://i.stack.imgur.com/gJ5hm.png

代码:

private void btnconectar_Click(object sender, EventArgs e)
{
if (!(empty(boxlogin.Text) && empty(boxsenha.Text)))
{
SqlCommand cmd = new SqlCommand("SELECT * from Usuarios where StrCmp(login, '" + boxlogin.Text + "')=0 and StrCmp(senha, '" + boxsenha.Text + "')=0",connection);
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 15;
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
nome = reader["nome"].ToString();
login = reader["login"].ToString();
senha = reader["senha"].ToString();
msg("Login realizado com sucesso!\nBem vindo(a), " + nome.Substring(0, nome.IndexOf(" ")),Color.Green, false);
connection.Close();
timer4.Start();
}
else
{
msg("Usuário e/ou senha incorretos!", Color.Red, false);
}
}
else msg("Os campos não podem ficar em branco!", Color.Red, false);
connection.Close();
}

执行后输出:

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll 'WindowsFormsApplication1.vshost.exe' (CLR v4.0.30319: WindowsFormsApplication1.vshost.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\mscorlib.resources\v4.0_4.0.0.0_pt-BR_b77a5c561934e089\mscorlib.resources.dll'. Module was built without symbols.

最佳答案

当您收到 SqlException 时,问题不在标记的行。它将位于执行查询的 ExecuteReader 行。

T-SQL中没有StrCmp函数,使用=运算符比较字符串。

您应该使用数据参数,当您将值连接到查询中而没有正确转义它们时,查询很容易受到 SQL 注入(inject)攻击。

要要求填写两个字段,您应该在条件中使用 || 运算符,而不是 && 运算符。

您没有关闭数据读取器,而是关闭了两次连接。您应该配置命令和数据读取器。安全处理该问题的最便捷方法是使用 using block 。

您不应该在生产代码中使用select *。选择要从查询中获取的字段。

private void btnconectar_Click(object sender, EventArgs e) {
if (!(empty(boxlogin.Text) || empty(boxsenha.Text))) {
using (SqlCommand cmd = new SqlCommand("SELECT nome, login, senha from Usuarios where login = @Login and senha = @Senha", connection)) {
cmp.Parameters.AddWithValue("@Login", boxlogin.Text);
cmp.Parameters.AddWithValue("@Senha", boxsenha.Text);
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 15;
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader()) {
if (reader.Read()) {
nome = reader["nome"].ToString();
login = reader["login"].ToString();
senha = reader["senha"].ToString();
msg("Login realizado com sucesso!\nBem vindo(a), " + nome.Substring(0, nome.IndexOf(" ")),Color.Green, false);
timer4.Start();
} else {
msg("Usuário e/ou senha incorretos!", Color.Red, false);
}
}
} else {
msg("Os campos não podem ficar em branco!", Color.Red, false);
}
}
connection.Close();
}

关于SQL Server 东西的 C# 代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29707938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com