C# 简单连接数据库并执行SQL查询语句

留着备用

private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = "Data Source=.;Password=123456;User ID=sa;Initial Catalog=guo;database=guo";
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "select * from dbo.[user]";
            SqlDataReader reader = cmd.ExecuteReader();
            
            while (reader.Read())
            {
                Object[] values = new Object[reader.FieldCount];
                int nCount = reader.GetValues(values);
                for (int i = 0; i != nCount; ++i)
                    listBox1.Items.Add(values[i]);
            }
                //             while (reader.Read())
                //             {
                //                     listBox1.Items.Add(reader[1]);
                //             }
                conn.Close();
        }
原文地址:https://www.cnblogs.com/guobbs/p/4202245.html