1

我在数据表中看不到添加的数据,这是代码:

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() 上给我一个错误;

4

2 回答 2

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();
于 2013-03-05T15:36:03.727 回答
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;
于 2013-03-05T15:45:15.937 回答