This is my first time working with DB.
I’ve decided to create a DB with two tables – “Team”, “Player”
I want to add a new player to the “Player” table.
The “Player” table consists of the following columns: ID(autonumber), FirstName, LastName, TeamID
In order to do so, I’ve created three text boxes for the FirstName, LastName, TeamID
Note that I did not treat the “ID” since it’s an autonumber and should be added automatically
The Button1_click should add the new row eventually.
Here’s my code:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
connection = new OleDbConnection(connectionString);
}
catch
{ }
try
{
connection.Open();
OleDbCommand command = new OleDbCommand("INSERT INTO Player VALUES ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')");
command.ExecuteNonQuery();
connection.Close();
}
catch
{ }
When you write an INSERT string that doesn’t include the column names you should specify every column in the values. In your case you need to add
However this code is wrong for another reason. Never write sql strings concatenating input text typed by the user. This will cause errors or, worse, lead to Sql Injection
There is another problem. If the TeamID field is a numeric field you need to convert the textbox3.text input in a numeric value to correctly use the AddWithValue method