作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我出于学习目的使用连接到 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(“嘿伙计,这个用户名已经被使用了!试试不同的东西)
最佳答案
关于您的代码示例的一些要点
using
语句中,这将为我处理。现在是一些代码。在此,我使用 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/
我是一名优秀的程序员,十分优秀!