14.16通过SqlDataRead方法和SqlDataSet方法 打印表格

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace _14._16本章小结及任务实施
{
class Program
{
static void Main(string[] args)
{
string constr = "Server=.;uid=sa;pwd=zqyo850619;database=company";
SqlConnection mycon = new SqlConnection(constr);

try
{
//通过DataReady打印数据
mycon.Open();
string sql = "select * from Clerk";
SqlCommand mycom = new SqlCommand(sql,mycon);
SqlDataReader mydr = mycom.ExecuteReader();
Console.WriteLine("使用SqlDataReader打印数据");
for(int i = 0; i < mydr.FieldCount; i++)
{
Console.Write(mydr.GetName(i)+"	");
}
Console.WriteLine();
while (mydr.Read())
{
for(int i = 0; i < mydr.FieldCount; i++)
{
Console.Write(mydr[i].ToString()+"	" );
}
Console.WriteLine();
}
mydr.Close();
Console.WriteLine("使用SqlDataSet打印输出");
SqlDataAdapter myda = new SqlDataAdapter(sql, mycon);
DataSet myds = new DataSet();
myda.Fill(myds, "Clerk");
foreach(DataTable table in myds.Tables)
{
foreach(DataColumn col in table.Columns)//输出字段名
{
Console.Write(col.ColumnName+"	");

}
Console.WriteLine();
foreach(DataRow row in table.Rows) //迭代每行
{
foreach(DataColumn col in table.Columns)
Console.Write(row[col]+"	");
Console.WriteLine();
}
}

}
catch(Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
finally
{
mycon.Close();
}
Console.ReadKey();
}
}
}
原文地址:https://www.cnblogs.com/zqyo2000z/p/5356937.html