-1

私は初心者の C# プログラマーです。C#でゲームを作ってみました。私の登録ページでエラーが発生しました。ExecuteNonQuery: Connection property has not been initializedat at this line "int result = command.ExecuteNonQuery();".Here は私の C# コードです。この問題を解決するのを手伝ってください。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WiimoteTest
{
public partial class regispage : Form
{

    private SqlConnection connection;
    private string sql;
    private SqlCommand command = new SqlCommand();



    public regispage()
    {
        InitializeComponent();
    }

    private void back_Click(object sender, EventArgs e)
    {
        startpage back = new startpage();
        back.Show();
        this.Close();
    }

    private void regispage_Load(object sender, EventArgs e)
    {
        string conStr = @"Data Source=.\SQLEXPRESS;
                        AttachDbFilename=C:\Users\vaio\Downloads\Compressed\WiimotLib_1.7\WiimotLib_1.7\samples\WiimoteTestCS_5_AllpagePuppyGameTestBirdResizepicTestDB\Angee.mdf;
                        Intregrated Security=True;User Instance=True;";
        connection = new SqlConnection(conStr);
        if (connection.State == ConnectionState.Closed)
        {
            connection.Open();
        }
    }

    private bool IsCompleteData()
    {
        string errMsg = "";
        if (username.Text == "")
        {
            errMsg = "Please input username";
        }
        else if (password.Text == "")
        {
            errMsg = "Please input password";
        }
        else if (fname.Text == "")
        {
            errMsg = "Please input firstname";
        }
        else if (lname.Text == "")
        {
            errMsg = "Please input lastname";
        }
        else if (nickname.Text == "")
        {
            errMsg = "Please input nickname";
        }
        else if (gender.SelectedIndex == -1)
        {
            errMsg = "Please select gender";
        }
        else if (age.Text == "")
        {
            errMsg = "Please input age";
        }
        else if (symptom.Text == "")
        {
            errMsg = "Please input symptom";
        }

        if (errMsg == "")
        {
            return true;
        }
        else
        {
            MessageBox.Show(errMsg);
            return false;
        }
    }

    private void AddParamterValues()
    {
        command.Parameters.AddWithValue("username", username.Text);
        command.Parameters.AddWithValue("password", password.Text);
        command.Parameters.AddWithValue("fname", fname.Text);
        command.Parameters.AddWithValue("lname", lname.Text);
        command.Parameters.AddWithValue("nickname", nickname.Text);
        command.Parameters.AddWithValue("gender", gender.SelectedItem.ToString());
        command.Parameters.AddWithValue("age", age.Text);
        command.Parameters.AddWithValue("symptom", symptom.Text);
    }

    private void submit_Click(object sender, EventArgs e)
    {
        if (!IsCompleteData())
        {
            return;
        }

        InsertData();


    }

    private void InsertData()
    {
        using (var connection = new SqlConnection())
        using (var command = connection.CreateCommand())
        {
            sql = @"INSERT INTO User(username, password, fname, lname, nickname, gender, age, symptom) 
              VALUES(@username, @password, @fname, @lname, @nickname, @gender, @age, @symptom),this.connection";

            **connection.Open();**

            var affectedRows = command.ExecuteNonQuery();

            command.Parameters.Clear();
            command.CommandText = sql;

            AddParamterValues();

            if (affectedRows < 1)
            {
                MessageBox.Show("Error to insert data");
                return;
            }
            else
            {
                MessageBox.Show("Insert data complete");
                menupage submit = new menupage();
                submit.Show();
                this.Close();
            }
        }
    }

    private void regispage_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (connection.State == ConnectionState.Open)
        {
            connection.Close();
        }
    }

}

}

4

3 に答える 3

2

クラス レベルのデータ クライアント オブジェクトはありません。できるだけ早く作成して破棄してください。

private void InsertData()
{
    using (var connection = new SqlConnection("YOUR_CONNECTION_STRING_HERE"))
    using (var command = connection.CreateCommand())
    {
        // populate command details

        connection.Open();

        var affectedRows = command.ExecuteNonQuery();

        // do whatever
    }
}

私の推奨事項を使用すると、次の行を取り除くことができます。

private SqlConnection connection;
private string sql;
private SqlCommand command = new SqlCommand();

...そして、すべてのコンパイラ エラーを (コードを削除して) 修正したら、準備完了です。

于 2013-03-19T16:06:19.443 に答える
1

コマンドにどの接続を使用するかを指示していません。

于 2013-03-19T16:04:43.397 に答える
0

Note that in general, you should avoid opening a connection and leaving it open, especially in a web or other multi-user, multi-threaded application. By default, connections are pooled (which is to say they remain open and available for use within the app domain whenever a connection is made using the exact same connect string value). Just create the connection needed, build and execute the command and Close()/Dispose() of the connection as fast as possibly and let the infrastructure worry about what's happening under the hood.

The general scheme for executing SQL is something like this:

public DataTable executeMyStoredProcedure()
{
  DataTable dt = new DataTable() ;
  string connectString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;" ;

  using ( SqlConnection connection = new SqlConnection(connectString) )
  using ( SqlCommand cmd = connection.CreateCommand() )
  using ( SqlDataAdapter sda = new SqlDataAdapter( cmd ) )
  {
    cmd.CommandText = "dbo.myStoredProcedure" ;
    cmd.CommandType = CommandType.StoredProcedure;

    // add your parameters here

    sda.Fill( dt ) ;

    connection.Close() ; // redundant, FWIW, since it will be closed via Dispose() when control leaves the using block.

  }

  return dt ;
}

The format of the connection string will vary depending on what relational database you're talking to. See http://connectionstrings.com for an introduction to the minimal values you'll need for different providers and database types. It should be noted though, that connection strings have many different keys that can be set to configure the connection as desired.

And the code will vary depending on the how of your execution. There are several different ways you can execute your query.

于 2013-03-19T19:27:05.700 に答える