ExecuteReader: Connection 属性尚未初始化。

            string conn_str = "Data Source=.;integrated security=sspi;database=my_db;";
            using (SqlConnection conn = new SqlConnection(conn_str))
            {
                conn.Open();
                //MessageBox.Show("cool");
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "select * from t_user where username=@un ";
                    cmd.Parameters.Add(new SqlParameter("un",textBox1.Text));
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())


 
  

 
  

错误:ExecuteReader: Connection 属性尚未初始化。

解决办法:插入代码 cmd.Connection = conn 即可。

  string conn_str = "Data Source=.;integrated security=sspi;database=my_db;";
            using (SqlConnection conn = new SqlConnection(conn_str))
            {
                conn.Open();
                //MessageBox.Show("cool");
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "select * from t_user where username=@un ";

你可能感兴趣的:(ExecuteReader: Connection 属性尚未初始化。)