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)+"\t");
}
Console.WriteLine();
while (mydr.Read())
{
for(int i = 0; i < mydr.FieldCount; i++)
{
Console.Write(mydr[i].ToString()+"\t" );
}
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+"\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.ToString());
}
finally
{
mycon.Close();
}
Console.ReadKey();
}
}
}

 

posted @ 2016-04-05 21:28  前缘Q+7589848  阅读(281)  评论(0编辑  收藏  举报