我正在使用连接到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+"');";
Run Code Online (Sandbox Code Playgroud)
coma.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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2523 次 |
| 最近记录: |