C# C和SQL Server中的连接字符串

C# C和SQL Server中的连接字符串,c#,connection-string,sql-server-2017,C#,Connection String,Sql Server 2017,我的连接与数据源没有问题,因此它在这里给出了错误: 填充SelectCommand。尚未初始化连接属性 我怎样才能解决这个问题?这是我的代码: private void button1_Click(object sender, EventArgs e) { string sqlSelect = "select * from account" + "Where username ='" + txtUsername.Text + "' and p

我的连接与数据源没有问题,因此它在这里给出了错误:

填充SelectCommand。尚未初始化连接属性

我怎样才能解决这个问题?这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    string sqlSelect = "select * from account" +
                       "Where username ='" + txtUsername.Text + "' and password ='" + txtPassword.Text + " ' ";

    // khoi tao doi tuong command
    cmd = new SqlCommand(sqlSelect, InitCon)
            {
                CommandType = CommandType.Text
            };

    // khoi tao doi tuong adapter
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);

    // tao datable chua data
    DataTable dt = new DataTable();

    // su dung adapter do data vao table nay
    adapter.Fill(dt);     // error occurs near here

    // binding eridview voi table
    dgwAccount.DataSource = dt;
}

谢谢您的帮助。

您应该在执行命令之前打开db连接。我建议你看看。此外,我在这里提供了一个示例代码,希望这对您有所帮助:

private static void CreateCommand(string query,string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            queryString, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}",
                reader[0], reader[1]));
        }
    }
}

从代码片段中可以看出,InitCon varibale未初始化,您可能需要检查


有关更多参考信息:

请尝试以下内容,它解决了代码中的几个问题:

防范风险,, 通过使用关键字来处理非托管资源, 还可以在您的查询文本中,在帐户和位置之间添加空格,您已经忘记了这一点。 见以下代码:

DataTable dt = new DataTable();

using(SqlConnection conn = new SqlConnection("connectionString"))
{
    using(SqlCommand com = new SqlCommand())
    {
        com.CommandText = "select * from account " + //don't forget about space here!
                                  "where username = @username and password = @password";
        com.Parameters.Add("@username", SqlDbType.VarChar).Value = txtUsername.Text;
        com.Parameters.Add("@password", SqlDbType.VarChar).Value = txtPassword.Text;
        com.Connection = conn;

        using(SqlDataAdapter adapter = new SqlDataAdapter(com))
        {
            conn.Open();
            adapter.Fill(dt);
        }
    }
}

那么,您试图放入数据表的SELECT命令是什么?SELECT命令是我在这里创建的连接字符串的数据源:字符串sqlSelect=SELECT*from account+Where username='+TXTSERNAME.Text+'和password='+txtPassword.Text+';//khoi tao doi tuong command cmd=new SqlCommandsqlSelect,InitCon{CommandType=CommandType.Text};dt或适配器如何处理这个查询?请将您的问题包括在内,因为我已对其进行了编辑。你能帮我一下吗?你没有添加任何内容。请将代码显示为文本,而不是图像显示我可以修复此处显示的错误:'SelectCommand属性在调用'Fill'之前尚未初始化。'I看不到连接。打开;和连接。关闭;有关适配器的说明。Filldt!另外,请显示有关InitConThanks的更多详细信息,以获取帮助,然后我将尝试。