I am an amateur in C# but I tried to connect to SQL database in C# and I am using Visual Studio 2015.
Trying to Insert on button click:
private void button1_Click_1(object sender, EventArgs e)
{
string hello = "Hello";
//insert data to database.
int rows;
string query = "INSERT INTO MyTable (name) VALUES (@username)";
try
{
using (myConnection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, myConnection))
{
myConnection.Open();
cmd.Parameters.AddWithValue("@username", hello);
rows = cmd.ExecuteNonQuery();
MessageBox.Show("ROWS AFFECTED: " + rows);
myConnection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The table has only two columns: ID
(AUTO_INCREMENT
) and name
(nchar(10)
)
Here is what I have tried: On button click, it shows:
Rows AFFECTED: 1
Which means there is no exception caught but When I click on "Show Table Data", the table is empty and it doesn't add a new record.
The Insert query works fine when I run it manually using query script.
The connection to the database is fine also as the SELECT
query runs perfectly fine.