2

ユーザー名とパスワードの 2 つのテキスト ボックスから値を取得する新しいユーザー フォームを簡単に作成します。button2 クリック イベントは、これらの値を取得し、データベースのユーザー テーブルに挿入する必要があります。ただし、コードを実行すると、データが追加されたことを示すメッセージ ボックスが表示され、VS2010 を使用してデータベース内のデータを表示できません。

VS でのデータベース接続のスクリーン ショットを参照してください。VS でデータベースのデータソースも作成しました。

何か案は?

とても有難い。

private void button2_Click(object sender, EventArgs e)
    {
        string username = txtUsername.Text;
        string password = txtPassword.Text;
        string sqlquery;
        string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename='C:\Users\Nick\Documents\Visual Studio 2010\Projects\DebenhamsProjectOffice V.01\DebenhamsProjectOffice V.01\DebenhamsProjectOfficeDatabase.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
        SqlConnection cn = new SqlConnection(connection);
        try
        {
            cn.Open();
        }
        catch (Exception)
        {
            MessageBox.Show("Unable to connect to Database");
        }

        sqlquery = "INSERT INTO Users (Username, Password) VALUES ('" + txtUsername.Text + "','" + txtPassword.Text + "')";
        try
        {
            SqlCommand command = new SqlCommand(sqlquery, cn);
            command.Parameters.AddWithValue("Username", username);
            command.Parameters.AddWithValue("Password", password);
            command.Parameters.Clear();
            MessageBox.Show("User Added");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        txtUsername.Text = "";
        txtPassword.Text = "";
        cn.Close();
    }

ここに画像の説明を入力

4

3 に答える 3

5

User Instance と AttachDbFileName=のアプローチ全体に欠陥があります - せいぜい! .mdfVisual Studio でアプリを実行すると、ファイルが (App_Dataディレクトリから出力ディレクトリ (通常.\bin\debugはアプリが実行される場所) に) コピーされ、ほとんどの場合、問題なく動作しますが、間違ったINSERTものを見ているだけです。最後にmdfファイル

このアプローチに固執したい場合は、myConnection.Close()呼び出しにブレークポイントを設定してから、 .mdfSQL Server Mgmt Studio Express でファイルを調べてください。データがそこにあることはほぼ確実です。

私の意見では、本当の解決策は

  1. SQL Server Express をインストールします (とにかく、既に完了しています)。

  2. SQL Server Management Studio Express をインストールする

  3. SSMS Expressでデータベースを作成し、論理名を付けます (例: DebenhamsProjectOfficeDatabase)

  4. 論理データベース名(サーバー上で作成したときに指定) を使用して接続し、物理データベース ファイルとユーザー インスタンスをいじらないでください。その場合、接続文字列は次のようになります。

    Data Source=.\\SQLEXPRESS;Database=DebenhamsProjectOfficeDatabase;Integrated Security=True
    

    そして、それ以外はすべて以前とまったく同じです...

また、(a) SQL インジェクション攻撃の危険を回避し、(b) パフォーマンスを向上させるために、常にパラメーター化されたクエリを使用し、SQL ステートメントを連結しないでください (特にユーザー入力が含まれている場合はそうではありません!)。

于 2013-04-06T18:09:06.500 に答える
2

ステートメントの効果を得るには、Command.ExecuteNonQuery()を呼び出す必要があります。insert

try
{
      SqlCommand command = new SqlCommand(sqlquery, cn);
      command.Parameters.AddWithValue("Username", username);
      command.Parameters.AddWithValue("Password", password);
      command.ExecuteNonQuery();
      command.Parameters.Clear();
      MessageBox.Show("User Added");
}
catch (Exception ex)
{
      MessageBox.Show(ex.Message);
}
于 2013-04-06T18:08:55.013 に答える
1

コードの修正を試みるだけです。重要な要素もあれば、エレガントな要素もあります。試してみてください。うまくいくかもしれません。または、エラーの場所を指している可能性があります。

private void button2_Click(object sender, EventArgs e)
    {
        string username = txtUsername.Text;
        string password = txtPassword.Text;
        string sqlquery;

        //Put away the apostrophes and used twice double quotations for
        //the full path of the database file:
        string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename=""C:\Users\Nick\Documents\Visual Studio 2010\Projects\DebenhamsProjectOffice V.01\DebenhamsProjectOffice V.01\DebenhamsProjectOfficeDatabase.mdf"";Integrated Security=True;Connect Timeout=30;User Instance=True";
        SqlConnection cn = new SqlConnection(connection);

        /* Better to let the program fail than think it's open and moving on
        removed try, catch*/
        cn.Open();


        //Why using your TextBoxes values if you already created strings?
        //changed

        //you should also be careful users can't type something like "') in the      
        //textboxes or they may cause a SQL injection

        sqlquery = "INSERT INTO Users (Username, Password) VALUES ('" + username + "','" + password + "')";

        try
        {
            SqlCommand command = new SqlCommand(sqlquery, cn);
            /* unnecessary since you already built a query command.Parameters.AddWithValue("Username", username);
            command.Parameters.AddWithValue("Password", password);
            command.Parameters.Clear();   */

            //Missing!!
            command.ExecuteNonQuery();
            MessageBox.Show("User Added");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        //Elegance
        txtUsername.Clear();
        txtPassword.Clear();
        cn.Close();
    }
于 2013-04-06T19:15:34.943 に答える