C#编程-69:DataReader和DataSet读取数据库内容示例_彭世瑜_新浪博客
【摘要】
源码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.D...
源码如下:
- 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();
- }
- }
- }
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/109661792
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)