我正在使用Visual C#连接到MySQL进行学习,当他输入已存在的用户名时,我一直在向用户抛出错误。
将事物放入数据库的当前代码(一旦我的问题可能更多地关于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+"');";
coma.ExecuteNonQuery();
我想要做的是将“username.Text”(“username”是一个TextBox)与数据库的“test”表上的值进行比较,如果某个值匹配,则调用MessageBox.Show (“嘿伙计,这个用户名已经在使用了!尝试不同的东西)
答案 0 :(得分:5)
关于代码示例的一些要点
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();
}
}
答案 1 :(得分:1)
using (OdbcConnection connection = SomeMethodReturningConnection())
using (OdbcCommand command = SomeMethodReturningCommand())
{
command.Parameters.Add(new OdbcParameter("@username", username.Text));
command.CommandText = "Select Count(*) From Users where 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 OdbcParameter("@password", password.Text));
command.CommandText = "Insert Into Users (Username, Password) Values (?,?)**";
command.ExecuteNonQuery();
}
}
无论如何,谢谢!