首页 > 代码库 > 数据库的连接

数据库的连接

        private void button1_Click(object sender, EventArgs e)
        {
            //连接数据库
            string sqls = "server=.;database=schoolData;user=sa;pwd=";//.本机的地址,数据库的文件名,sa:登录用户名
            SqlConnection conn = new SqlConnection(sqls);//数据库连接类

            SqlCommand cmd = conn.CreateCommand();//数据库访问类
            cmd.CommandText = "select *from student";//书写t-sql语句

            conn.Open();//开启连接
            SqlDataReader dr = cmd.ExecuteReader();//执行访问返回数据
            while (dr.Read())//通过read下移指针一行行读取数据
            {
                ListViewItem lt = new ListViewItem();
                lt.Text = dr["sno"].ToString();//数据库中的类
                lt.SubItems.Add(dr["sname"].ToString());
                lt.SubItems.Add(dr["ssex"].ToString());
                lt.SubItems.Add(dr["class"].ToString());
                listView1.Items.Add(lt);
            }
            conn.Close();//关闭连接

 

 

数据库单项查询的连接


        private void button1_Click(object sender, EventArgs e)
        {
            //连接数据库
            string sqls = "server=.;database=schoolData;user=sa;pwd=";
            SqlConnection conn = new SqlConnection(sqls);//数据库连接类

            SqlCommand cmd = conn.CreateCommand();//数据库访问类
            cmd.CommandText = "select *from " + textBox1.Text;//书写t-sql语句

            conn.Open();//开启连接
            SqlDataReader dr = cmd.ExecuteReader();//执行访问返回数据
            int count = dr.FieldCount;
            listView1.Columns.Clear();
            listView1.Items.Clear();
            for (int j = 0; j < count; j++)
            {
                listView1.Columns.Add(dr.GetName(j));
                
            }
            while (dr.Read())//通过read下移指针一行行读取数据
            {
                ListViewItem lt = new ListViewItem();
                for (int i = 0; i < count; i++)
                {
                    if (i == 0)
                    {
                        lt.Text = dr[i].ToString();
                    }
                    else
                    {
                        lt.SubItems.Add(dr[i].ToString());
                    }
                }
                listView1.Items.Add(lt);

            }
            conn.Close();//关闭连接
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

数据库的连接