C# 和 SQL 服务器中的连接字符串

Connection String in C# and SQL Server

我的数据源连接没问题,所以这里出现错误:

Fill SelectCommand.Connection property has not been initialized.

我该如何解决?这是我的代码:

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

谢谢你帮助我。

你应该在执行命令之前打开数据库连接。我建议看一看here。我还在这里放了一个示例代码,希望这对您有所帮助:

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

从代码片段可以看出,Int 变量未初始化,您可能需要检查...

更多参考:https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx

试试下面,它解决了您的代码的几个问题:

  • 防止 SQL injection 风险,
  • 使用 using 关键字处理非托管资源,
  • 还在 accountwhere 之间的查询文本中添加 space,您忘记了。

见下面的代码:

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