SELECT is easy - you know how to do that already, or you should before you get to INSERT statements.
But first...don't do anything like that! Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
It's also a good idea to Dispose of Connection and Command objects - they are a scarce resource.
The easiest way is to use a
using
block:
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);
}
}