Reputation: 45
I cannot see the added data in the data table this is the code:
private void button1_Click(object sender, EventArgs e)
{
string t1 = textBox1.Text;
SqlCeConnection conn =
new SqlCeConnection(@"Data Source=|DataDirectory|\Database1.sdf");
conn.Open();
SqlCeCommand cmdInsert = conn.CreateCommand();
cmdInsert.CommandText = "INSERT TO table_name (Column1) VALUES (t1)";
cmdInsert.ExecuteNonQuery();
conn.Close();
}
It doesnt insert into data table after clicking on the button, it gives me an error on cmdInsert.ExecuteNonQuery();
Upvotes: 1
Views: 200
Reputation: 263683
because you query is not parameterized that's why you need to wrap it with single quotes,
cmdInsert.CommandText = "INSERT INTO table_name (Column1) VALUES ('" + t1 + "')";
the query above is prone to SQL Injection
, here's how to parameterized it:
cmdInsert.CommandText = "INSERT INTO table_name (Column1) VALUES (@t1)";
cmdInsert.Parameter.AddWithValue("@t1", t1);
cmdInsert.ExecuteNonQuery();
Upvotes: 5
Reputation: 19871
Recommend parameterizing t1
. See SqlCeCommand.Parameters
Parameterizing the values is a good practice to learn.
sample from link:
SqlCeConnection conn = new SqlCeConnection("Data Source = MyDatabase.sdf;");
conn.Open();
SqlCeCommand command = conn.CreateCommand();
// Create and prepare a SQL statement
//
command.CommandText = "INSERT INTO Region (RegionID, RegionDescription) VALUES (@id, @desc)";
SqlCeParameter param = null;
// NOTE:
// For optimal performance, make sure you always set the parameter
// type and the maximum size - this is especially important for non-fixed
// types such as NVARCHAR or NTEXT; In case of named parameters,
// SqlCeParameter instances do not need to be added to the collection
// in the order specified in the query; If however you use ? as parameter
// specifiers, then you do need to add the parameters in the correct order
//
param = new SqlCeParameter("@id", SqlDbType.Int);
command.Parameters.Add(param);
param = new SqlCeParameter("@desc", SqlDbType.NVarChar, 100);
command.Parameters.Add(param);
command.Parameters["@desc"].Size = 100;
Upvotes: 0