gpt4 book ai didi

c# - 如何在 C# 中将 SQL "Select"结果保存到变量中

转载 作者:行者123 更新时间:2023-11-29 04:12:47 24 4
gpt4 key购买 nike

我出于学习目的使用连接到 MySQL 的 Visual C#,但当用户键入已存在的用户名时,我一直向用户抛出错误。

将东西放入数据库的当前代码(它可能没用,一旦我的问题可能更多关于 SQL):

s = new sql(); // This calls a class that works as an adapter to connect form with the database
Conn = s.Connection;
Conn.Open();
coma = Conn.CreateCommand();
coma.CommandText = "INSERT INTO test.test (`user`,`password`) VALUES ('"+username.Text+"','"+password.Text+"');";

昏迷.ExecuteNonQuery();

我想做的是将“username.Text”(“username”是一个 TextBox)与数据库“test”表中的值进行比较,如果某些值匹配,则调用 MessageBox.Show(“嘿伙计,这个用户名已经被使用了!试试不同的东西)

最佳答案

关于您的代码示例的一些要点

  1. 你想确保你处理了你的连接和命令对象。对于我的回答,我将它们包装在 using 语句中,这将为我处理。
  2. 您不想使用 unsanitized inputs 访问数据库.我将在示例中使用参数化查询。
  3. 以纯文本形式存储密码不是一个好主意。 我不会演示更安全的技术,只知道 look for information about encrypting passwords 、盐键等。

现在是一些代码。在此,我使用 OleDb 对象,对您的特定数据库进行改造。当然,还要为表、列等提供适当的名称。

using (OleDbConnection connection = SomeMethodReturningConnection())
using (OleDbCommand command = SomeMethodReturningCommand())
{
command.Parameters.Add(new OleDbParameter("@username", username));
command.CommandText = "Select Count(*) From Users where Username = @username";
connection.Open();
int output = (int)command.ExecuteScalar();

if (output > 0)
{
// username already exists, provide appropriate action
}
else
{
// perform insert
// note: @username parameter already exists, do not need to add again
command.Parameters.Add(new OleDbParameter("@password", password));
command.CommandText = "Insert Into Users (Username, Password) Values (@username, @password)";
command.ExecuteNonQuery();
}
}

关于c# - 如何在 C# 中将 SQL "Select"结果保存到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5752314/

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