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

时间:2018-07-22 05:00:43

标签: c# connection-string sql-server-2017

我与数据源的连接还可以,所以它给了我这里的错误:

  

填充SelectCommand.Connection属性尚未初始化。

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

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

谢谢您的帮助。

3 个答案:

答案 0 :(得分:1)

尝试以下方法,可以解决您的代码中的几个问题:

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

请参见以下代码:

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

答案 1 :(得分:0)

您应该在执行命令之前打开数据库连接。我建议看看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]));
        }
    }
}

答案 2 :(得分:0)

从代码片段可以看出,InitCon varibale未初始化,您可能想检查一下...

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