0

データベースにデータを保存する C# ソフトウェアがありますが、プログラムを実行してデータを保存しようとするたびに、このメッセージが表示されます。何か助けてください。

ここに画像の説明を入力

try
{
    SqlConnection cnn = new SqlConnection(@"Data  Source=.\SQLEXPRESS;
        AttachDbFilename=C:\Users\Hp\Documents\Visual Studio 2010\Projects\Bank_System\Bank_System\Bank_System.sdf;
        Integrated Security=True;User Instance=True");
    cnn.Open();
    SqlCommand cmd1 = 
       new SqlCommand("insert into user values('" + 
           textBox6.Text + "','" + textBox1.Text + "','" + textBox4.Text + "'," + 
           textBox3.Text + ",'" + textBox2.Text +  "','" + textBox5.Text + "')",
           cnn);
    SqlDataReader dr1 = cmd1.ExecuteReader();
    dr1.Close();
    MessageBox.Show(" Record inserted ", " information inserted");
    cnn.Close();
}
catch (SqlException ex)
{
    MessageBox.Show(ex.Message);
}
4

2 に答える 2

0

SDF ファイルを使用しています。このファイルは SQL Server Compact 用であり、SQL Server Express (またはフル) 用ではありません。

この場合、接続文字列は次のようになります。

 @"Data Source=<fullpath_and file_to_your_sdf_file>;Persist Security Info=False;"

C# では、バックスラッシュなどの特殊文字を含む文字列の前にそのままの文字を追加する必要があることに注意してください。

Sql Server Compact を使用するには、Microsoft ダウンロードから必要なライブラリをインストールし、適切なクラスを使用する必要があります。そのため、SqlConnection および SqlCommand クラスを削除し、SqlCeConnection および SqlCeCommand を使用します (アプリで使用される他のデータ クライアント クラスについても同様です)。

もちろん、SqlCeConnection クラスは、この異なる接続文字列の構文を理解して、SDF ファイルを操作できるようにします。

そうは言っても、sql コマンドをビルドするコードを修正してください。コードのように文字列連結を使用すると、エラーの安全なレシピになります。解析エラー (文字列内の引用符は構文を壊します) から、 Sql インジェクションのようなより深刻なエラーまで

これは、パラメーター化されたクエリを使用したアプローチである可能性があります....

try
{
    string cmdText = "insert into user values(@p1, @p2, @p3,@p4,@p5,@p6)";
    using(SqlCeConnection cnn = new SqlCeConnection(@"Data Source=C:\Users\Hp\Documents\Visual Studio 2010\Projects\Bank_System\Bank_System\Bank_System.sdf;Integrated Security=True"))
    using(SqlCeCommand cmd1 = new SqlCeCommand(cmdText, cnn))
    {
        cnn.Open();
        cmd.Parameters.AddWithValue("@p1", textBox6.Text);
        cmd.Parameters.AddWithValue("@p2", textBox1.Text);
        cmd.Parameters.AddWithValue("@p3", textBox4.Text);
        cmd.Parameters.AddWithValue("@p4", textBox3.Text);
        cmd.Parameters.AddWithValue("@p5", textBox2.Text);
        cmd.Parameters.AddWithValue("@p6", textBox5.Text);
        cmd1.ExecuteNonQuery();
        MessageBox.Show(" Record inserted ", " information inserted");
     }
}
catch (SqlException ex)
{
    MessageBox.Show(ex.Message);
}
于 2014-05-17T09:33:08.113 に答える