我无法在数据表中看到添加的数据 这是代码:
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();
}
它不会插入数据表 点击按钮后,它给我一个错误 cmdInsert.ExecuteNonQuery();
答案 0 :(得分:5)
因为你的查询没有参数化,所以你需要用单引号包装它,
cmdInsert.CommandText = "INSERT INTO table_name (Column1) VALUES ('" + t1 + "')";
上面的查询倾向于SQL Injection
,以下是如何对其进行参数化:
cmdInsert.CommandText = "INSERT INTO table_name (Column1) VALUES (@t1)";
cmdInsert.Parameter.AddWithValue("@t1", t1);
cmdInsert.ExecuteNonQuery();
答案 1 :(得分:0)
建议参数化t1
。见SqlCeCommand.Parameters
参数化这些值是一个很好的实践。
来自链接的示例:
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;