源码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace SQLLastTest { class Program { static void Main(string[] args) { //连接字符串 SqlConnectionStringBuilder sqlsb = new SqlConnectionStringBuilder(); sqlsb.DataSource = @"(localdb)\Projects"; sqlsb.IntegratedSecurity = true; sqlsb.InitialCatalog = "company"; //连接数据库,采用try...catch形式 SqlConnection sqlcon = new SqlConnection(sqlsb.ToString()); try { sqlcon.Open(); string sql = "select * from clerk"; SqlCommand sqlcom = new SqlCommand(sql,sqlcon); //使用SqlDataReader打印表信息 SqlDataReader sqlread = sqlcom.ExecuteReader(); Console.WriteLine("使用SqlDataReader打印表信息:"); for (int i = 0; i < sqlread.FieldCount; i++) { Console.Write(sqlread.GetName(i)+"\t"); } Console.WriteLine(); while (sqlread.Read()) { for (int i = 0; i < sqlread.FieldCount; i++) { Console.Write(sqlread[i].ToString()+"\t"); } Console.WriteLine(); } sqlread.Close(); //使用DataSet打印表信息 Console.WriteLine("使用DataSet打印表信息:"); SqlDataAdapter sqladp = new SqlDataAdapter(sql,sqlcon); DataSet dataSet = new DataSet(); sqladp.Fill(dataSet,"clerk"); foreach (DataTable table in dataSet.Tables) { foreach (DataColumn col in table.Columns) { Console.Write(col.ColumnName+"\t"); } Console.WriteLine(); foreach (DataRow row in table.Rows) { foreach (DataColumn col in table.Columns) { Console.Write(row[col]+"\t"); } Console.WriteLine(); } } } catch(Exception ex) { Console.WriteLine(ex.Message); } finally { sqlcon.Close(); } Console.ReadKey(); } } }