C#编程-69:DataReader和DataSet读取数据库内容示例
2024-06-25 09:51:41 阅读次数:19
编程开发
源码如下:
- 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();
- }
- }
- }
版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.51cto.com/mouday/3044914,作者:彭世瑜,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。
上一篇:C#编程-147:线程基础
下一篇:JavaFX使用maven-assembly-plugin打包