C#中sqlDataRead 的三种方式遍历读取各个字段数值的方法
数据库的查询分析器中写上如下代码:
create table studentname ( id int primary key identity(1,1) not null , name nvarchar(500) not null ) insert into studentname values('long') insert into studentname values('long') insert into studentname values('long') insert into studentname values('long') insert into studentname values('long') insert into studentname values('chao') insert into studentname values('chao')
--sql server 2012 通过。
---------------------------------------------------------------------------------------------------
以下是第一种方法:
using System.Data; using System.Data.SqlClient; string constr = "server=localhost;uid=sa;pwd=longshicheng;database=Student"; SqlConnection conn = new SqlConnection(constr); SqlCommand cmd = new SqlCommand("select * from studentname", conn); conn.Open(); SqlDataReader rdr = cmd.ExecuteReader(); string makestr = ""; DataTable table = new DataTable(); table.Load(rdr); //数据表装入 dataReader 。 string result=""; for (int i = 0; i < table.Rows.Count; i++) // 遍历行 { for (int j = 0; j < table.Columns.Count; j++) //遍历列 { result += table.Rows[i][j].ToString(); //逐行逐列显示每个单元格的数值。 } result += Environment.NewLine; //一行遍历完成就写入回车。 } txtlab.Text = result; /***************************************************************/
以下是第二种方法:
string constr = "server=localhost;uid=sa;pwd=longshicheng;database=Student"; SqlConnection conn = new SqlConnection(constr); SqlCommand cmd = new SqlCommand("select * from studentname", conn); conn.Open(); SqlDataReader rdr = cmd.ExecuteReader(); string makestr = ""; for (int k = 0; k < rdr.FieldCount; k++) //获取字段名称 { makestr += rdr.GetName(k) + "\t"; //载入字段名称 } makestr += Environment.NewLine; //换行 makestr = makestr + "---------------------------------------------"+Environment.NewLine; while (rdr.Read()) //逐行读取每一笔记录 { for (int t = 0; t < rdr.FieldCount; t++) //逐列读出 { makestr = makestr + rdr[t].ToString() + "\t"; //累加每一行,也就是逐个字段读出对应的数值 } makestr = makestr + Environment.NewLine; //又一行 } txtinfo.Text = makestr; rdr.Close(); //关闭 conn.Close(); }
以下是第三种方法:
string constr = "server=localhost;uid=sa;pwd=longshicheng;database=Student"; SqlConnection conn = new SqlConnection(constr); SqlCommand cmd = new SqlCommand("select * from studentname", conn); conn.Open(); SqlDataReader rdr = cmd.ExecuteReader(); string makestr = ""; for (int k = 0; k < rdr.FieldCount; k++) //获取字段名称 { makestr += rdr.GetName(k) + "\t"; //载入字段名称 } makestr += Environment.NewLine; //换行 makestr = makestr + "---------------------------------------------" + Environment.NewLine; while (rdr.Read()) //逐行读取每一笔记录 { makestr = makestr + rdr.GetValue(0) + " \t" + rdr.GetValue(1).ToString() + "\t"; makestr = makestr + Environment.NewLine; } txtother.Text = makestr; rdr.Close(); //关闭 conn.Close();
以上所有方法运行结果均如下:
id name
---------------------------------------------
1 long
2 long
3 long
4 long
5 long
6 chao
7 chao
总结
以上所述是小编给大家介绍的C#中sqlDataRead 的三种方式遍历读取各个字段数值的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!
赞 (0)