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

パラメータ化を推奨しますt1SqlCeCommand.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 に答える