本文介绍了防止重复名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,
我使用此代码在此表中添加名称
Hello ,
I using this code to add name in this table
private void button1_Click(object sender, EventArgs e)
{
string Coonstring = "datasource=localhost;port=3306;username=root;password=****;Charset=utf8";
string cmd = "Insert into project.name_registry (name ) values('" + this.txt.Text + "');";
MySqlConnection connectionDatabase = new MySqlConnection(Coonstring);
MySqlCommand cmddata = new MySqlCommand(cmd, connectionDatabase);
MySqlDataReader myreader;
try
{
connectionDatabase.Open();
myreader = cmddata.ExecuteReader();
MessageBox.Show("Done");
while (myreader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
当我按下此按钮时我需要(添加按钮)检查是否显示插入名称消息框告诉我名称是否存在并阻止添加。如果没有告诉我插入完成。我怎么能这样做。
问候
I need when I press on this button ( Add button) check if the insert name found messagebox appear tell my the name exists and prevent the add. If not tell me the insert Done. How i can do this.
Regards
推荐答案
SELECT * FROM name_registry WHERE name = @name
不要连接字符串来执行SQL,因为您可以接受SQL注入。
Don't concatenate strings to do your SQL because you are open to SQL injections.
cmd.Parameters.AddWithValue("@name", txt.Text);
然后检查你的datareader是否有行。如果确实如此,那意味着它已经存在,那么你可以做任何你需要做的事情。
Then check if your datareader has rows. If it does, that means it already exists and then you can do whatever you need to do at that point.
string Coonstring = "datasource=localhost;port=3306;username=root;password=****;Charset=utf8";
using (MySqlConnection connectionDatabase = new MySqlConnection(Coonstring))
{
try
{
connectionDatabase.Open();
using (MySqlCommand select = new MySqlCommand("SELECT COUNT(*) FROM project.name_registry WHERE Name=@NM", connectionDatabase))
{
select.Parameters.AddWithValue("@NM", txt.Text);
if (select.ExecuteScalar() != 0)
{
MessageBox.Show("Name exists");
return;
}
}
using (MySqlCommand cmddata = new MySqlCommand("INSERT INTO project.name_registry (name) VALUES(@NM)", connectionDatabase))
{
cmddata.Parameters.AddWithValue("@NM", txt.Text);
cmddata.ExecuteNonQuery();
MessageBox.Show("Done");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void UpdateTable(string connStr, string nameVal)
{
using (MySqlConnection conn = new MySqlConnection(connStr))
{
conn.Open();
string cmdStr = @"insert into project.name_registry(name)
select * from (select @pname) as tmp
where not exists (select * from project.name_registry where name=@pname)";
using (MySqlCommand cmd = new MySqlCommand(cmdStr, conn))
{
cmd.Parameters.AddWithValue("@pname", nameVal);
if (cmd.ExecuteNonQuery() > 0)
{
Console.WriteLine("added");
}
else
{
Console.WriteLine("exists");
}
}
}
}
这篇关于防止重复名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!