数据库不同表不同列的查询
第一个显示在listview中
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsFormsApplication3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("server=.;database="+textBox1.Text+";uid=sa;pwd=123"); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select * from "+textBox2.Text; conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { listView1.Columns.Clear();//先清空一下列名 for (int i = 0; i < dr.FieldCount; i++) { listView1.Columns.Add(dr.GetName(i));//插入列名,dr.GetName(i)获取指定列的列名 } listView1.Items.Clear();//清空一下行 while (dr.Read())//读取到行 { ListViewItem lt = new ListViewItem();//新建一行的对象 for (int i = 0; i < dr.FieldCount; i++) { if (i == 0) { lt.Text = dr[i].ToString();//行第一列的数值 } else { lt.SubItems.Add(dr[i].ToString());//行第一列之后的数值 } } listView1.Items.Add(lt);//把这一行加入Items集合 } } conn.Close(); } } }
第二个显示在DataGridView中
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsFormsApplication3 { public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("server=.;database=" + textBox1.Text + ";uid=sa;pwd=123"); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select * from " + textBox2.Text; conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); DataTable dt = new DataTable();//创建DateTable新实例 if (dr.HasRows) { dt.Columns.Clear();//清空一下dt中的列 for (int i = 0; i < dr.FieldCount; i++) { dt.Columns.Add(dr.GetName(i));//添加列名 } while (dr.Read()) { DataRow dtr = dt.NewRow();//按dt的构架,新建行新实例 for (int i = 0; i < dr.FieldCount; i++) { dtr[i] = dr[i];//添加行中的数据,行的第一个数值对应dr.Read()读取到的第一个格数值,索引相对于 } dt.Rows.Add(dtr); } } dataGridView1.DataSource = dt;//最后把dt赋给dataGridView1 conn.Close(); } } }