ADO.NET数据库访问技术(转)
时间:2021-07-01 10:21:17
帮助过:3人阅读
using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Xml.Linq;
6 using System.Windows.Forms;
7 using System.Data.SqlClient;
8 using System.Data;
9
10 namespace xmlTest
11 {
12 class Program
13 {
14 static void Main(
string[] args)
15 {
16 try
17 {
18 //定义连接字符串
19 string connString =
"server=.;database=gpweb;uid=sa;pwd=123456";
20 //定义查询语句
21 string cmdStr =
"select * from WebUser where UserName=‘lcyuhe‘;";
22
23 //保存查询结果
24 DataSet ds =
new DataSet();
25
26 //创建Connection对象
27 SqlConnection connection =
new SqlConnection(connString);
28 //打开数据库
29 connection.Open();
30
31 //command对象可以用来对数据库发出具体的操作指令,例如对数据库的查询、增加、修改、删除
32 SqlCommand command =
new SqlCommand();
33 command.Connection =
connection;
34 command.CommandText =
cmdStr;
35 //int affects = command.ExecuteNonQuery();
36
37 SqlDataAdapter adapter =
new SqlDataAdapter(command);
38 adapter.Fill(ds);
39
40 DataTableCollection dtc =
ds.Tables;
41 //遍历查询结果
42 foreach (DataTable dt
in dtc)
43 {
44 Console.WriteLine(
"表:" +
dt.TableName);
45 foreach (DataRow drow
in dt.Rows)
46 {
47
48 //遍历列
49 //foreach (var item in drow.ItemArray)
50 //{
51 // Console.WriteLine(item);
52 //}
53
54 // 获取或设置存储在由名称指定的列中的数据
55 Console.WriteLine(
"username:" + drow[
"username"]);
56 }
57 }
58
59
60 //Console.WriteLine("受影响的行数:{0}", affects);
61
62 //对数据库操作完毕后关闭数据库连接
63 connection.Close();
64
65
66 }
67 catch (Exception ex)
68 {
69 Console.WriteLine(ex.Message);
70 throw;
71 }
72 Console.WriteLine(
"====================================================");
73 Console.ReadKey();
74 }
75 }
76 }
转自:http://www.360doc.com/content/13/0606/09/10504424_290840282.shtml
ADO.NET数据库访问技术(转)
标签: