如何解决ExecuteNonQuery:Connection属性尚未初始化

时间:2013-03-19 16:02:07

标签: c# executenonquery

我是新手C#程序员。我尝试用C#制作游戏。在我的注册页面上有一些错误。它说ExecuteNonQuery:Connection属性尚未在这行“int result = command.ExecuteNonQuery();”中初始化。这是我的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();
        }
    }

}

}

3 个答案:

答案 0 :(得分:1)

您没有告诉Command使用哪个连接。

答案 1 :(得分:1)

没有类级数据客户端对象。尽快创建和处理它们。

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();

...一旦你修复了所有的编译错误(通过删除代码),你就会好起来。

答案 2 :(得分:0)

请注意,一般情况下,应避免打开连接并使其保持打开状态,尤其是在Web或其他多用户多线程应用程序中。默认情况下,连接是池化(也就是说,只要使用完全相同的连接字符串值建立连接,它们就会保持打开并可在应用程序域中使用)。只需创建所需的连接,尽可能快地构建并执行命令和Close() / Dispose()连接,让基础设施担心引擎盖下发生的事情。

执行SQL的一般方案是这样的:

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 ;
}

连接字符串的格式将根据您正在与之交谈的关系数据库而有所不同。有关不同提供商和数据库类型所需的最小值的介绍,请参阅http://connectionstrings.com。但应该注意,连接字符串有许多不同的密钥,可以根据需要设置它们来配置连接。

代码会因执行的 而异。您可以通过多种不同的方式执行查询。