使用ADO.NET查询和操作数据

StringBuilder类: 用来定义可变字符串
StringBuilder sb = new StringBuilder("");
//追加字符串
sb.Append("World");
sb.Append("!");
//W2orld
sb.Insert(2, "2");
//原字符串:Wo2rld! 截取之后:W2rld! 
sb.Remove(1, 2);
//ToString()
Console.WriteLine(sb.ToString());

查询学生记录数
//打开数据库连接
con.Open();
//使用StringBuilder追加SQL语句
StringBuilder sb = new StringBuilder();
sb.Append("select ");
sb.Append(" Count(*) ");
sb.Append(" from ");
sb.Append("[Student]");
Console.WriteLine(sb.ToString());
//创建一个SqlCommand对象
SqlCommand com = new SqlCommand(sb.ToString(),con);
Console.WriteLine((int)com.ExecuteScalar());

DataReader:从数据源中检索只读、只进的数据流,每次读取一行数据

StringBuilder sb = new StringBuilder();
sb.AppendLine("select");
sb.AppendLine("[StudentNo]");
sb.AppendLine(",[StudentName]");
sb.AppendLine("from");
sb.AppendLine("[Student]");
SqlCommand com = new SqlCommand(sb.ToString(), con);
//从数据源中检索只读、只进的数据流
return com.ExecuteReader();

SqlDataReader reader=GetStudentInfo();
while (reader.Read())
{
Console.WriteLine("{0}\t{1}",reader["StudentNo"],reader["StudentName"]);
}
reader.Close();

ExecuteNonQuery():

StringBuilder sb = new StringBuilder();
sb.AppendLine("Insert into");
sb.AppendLine("[Grade]([GradeName])");
sb.AppendLine("Values('" + gradeName + "')");
//3.创建一个SqlCommand
SqlCommand com = new SqlCommand(sb.ToString(),con);
//4.返回执行结果
return com.ExecuteNonQuery();

Student stu = new Student();
Console.WriteLine("请输入年级名称:");
string gradename = Console.ReadLine();
int count = stu.AddGrade(gradename);
if (count > 0)
{
Console.WriteLine("success!");
}
else
{
Console.WriteLine("success mother!");
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
class Test
    {
        string connString = "Data Source = .;Initial Catalog= Library;User Id = Sa;Pwd = asiga0.";
        //判断用户
        public bool CheckUser(string UserId, string Password) {
            String s = "select count(*) from user1 where loginid='" + UserId + "'and loginpwd = '" + Password + "'";//空格错误!
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand comm = new SqlCommand(s, conn);
            try
            {
                conn.Open();
                if ((int)comm.ExecuteScalar()>0
                    )
                {
                    Console.WriteLine("登陆成功");
                    return true;
                }
                else
                {
                    Console.WriteLine("登录失败");
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
            finally
            {
                conn.Close();
            }
        }
 
        //主菜单
        public void List() {
            do
            {
                Console.WriteLine("====请选择操作键====");
                Console.WriteLine("1.查看全部图书");
                Console.WriteLine("2.插入图书信息");
                Console.WriteLine("3.修改图书信息");
                Console.WriteLine("4.删除图书信息");
                Console.WriteLine("5.退出");
                Console.WriteLine("===============");
                int i = int.Parse(Console.ReadLine());
                switch (i)
                {
                    case 1:
                        One();
                        break;
                    case 2:
                        Two();
                        break;
                    case 3:
                        Three();
                        break;
                    case 4:
                        Four();
                        break;
                    case 5:
                        Console.WriteLine("谢谢使用,再见!");
                        return;
                    default:
                        break;
                }
                Console.WriteLine("继续吗?(Y/N)");
                if (!Console.ReadLine().ToLower().Trim().Equals("y"))
                {
                    break;
                }
            while (true);
        }
        public void One() {
            SqlConnection conn = new SqlConnection(connString);
           
            try
            
                String s = "select book.id,book.name,booktype.typename,book.number,book.price from book,booktype where book.typle=booktype.typle";
                Console.WriteLine("------------------------------------------------");
                Console.WriteLine("编号\t名称\t\t类别\t数量\t价格");
                Console.WriteLine("------------------------------------------------");
                SqlCommand comm = new SqlCommand(s, conn);
                conn.Open();
                SqlDataReader rd = comm.ExecuteReader();
                while (rd.Read())
                {
                    Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", rd["id"], rd["name"], rd["typename"], rd["number"], rd["price"]);//前面不能加" . "
                }
                rd.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
 
            }
            finally
            {
                conn.Close();
            }
        }
        public void Two() {
                SqlConnection conn = new SqlConnection(connString);
                try
                {
                    Console.WriteLine("请输入图书编号");
                    int Id = int.Parse(Console.ReadLine());
                    if (GetBookByID(Id))
                    {
                        Console.WriteLine("图书记录已存在,请重新输入!");
                        return;
                    }
                    Console.WriteLine("请输入图书名称");
                    string name = Console.ReadLine();
                    Console.WriteLine("请插入图书类型编号");
                    int type = int.Parse(Console.ReadLine());
                    if (GetBookTypeByID(type)) { }
                    else { Console.WriteLine("不存在,请重新输入"); return; }
                    Console.WriteLine("请插入图书数量");
                    int number = int.Parse(Console.ReadLine());
                    Console.WriteLine("请输入图书单价");
                    float price = float.Parse(Console.ReadLine());
                    String s = string.Format("insert book(id,name,typle,number,price) values({0},'{1}',{2},{3},{4})", Id, name, type, number, price);
                    SqlCommand comm = new SqlCommand(s, conn);
                    conn.Open();//忘记开启
                    if (comm.ExecuteNonQuery() > 0)
                    {
                        Console.WriteLine("插入成功!");
                    }
                    else
                    {
                        Console.WriteLine("插入失败");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    conn.Close();
                }
        }
        public bool GetBookByID(int bookId) {
                SqlConnection conn = new SqlConnection(connString);
                string s = "select id from book where id=" + bookId;
                SqlCommand comm = new SqlCommand(s, conn);
                conn.Open();
                SqlDataReader rd = comm.ExecuteReader();
                try
                {
                    if (rd.Read())
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return true;
                }
                finally
                {
                    rd.Close();
                    conn.Close();
                }
        }
        public bool GetBookTypeByID(int typeId) {
            SqlConnection conn = new SqlConnection(connString);
            string s = "select typle,typename from booktype where typle=" + typeId;
            SqlCommand comm = new SqlCommand(s, conn);
            conn.Open();
            SqlDataReader rd = comm.ExecuteReader();
            try
            {
                if (rd.Read())
                {
                    Console.WriteLine("{0}\t{1}", rd["typle"], rd["typename"]);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
            finally
            {
                rd.Close();
                conn.Close();
            }
        }
        public void Three() {
            Console.WriteLine("请输入图书编号");
            int id = int.Parse(Console.ReadLine());
            if (GetBookByID(id))
            {
                Console.WriteLine("请输入修改后的价格($.00):");
                float f = float.Parse(Console.ReadLine());
                if (ChangePrice(id, f) > 0)
                {
                    Console.WriteLine("修改成功");
                }
                else
                {
                    Console.WriteLine("修改失败");
                }
            }
            else
            {
                Console.WriteLine("不存在该编号,请重新输入");
                return;
            }  
        }
        public int ChangePrice(int id,float price) {
            SqlConnection conn = new SqlConnection(connString);
            try
            {
                String s = string.Format("update book set price ={0} where id={1}", price, id);
                SqlCommand comm = new SqlCommand(s, conn);
                conn.Open();
                return comm.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return -1;
            }
            finally
            {
                conn.Close();
            }
        }
        public void Four() {
            Console.WriteLine("请输入图书编号");
            int id = int.Parse(Console.ReadLine());
            if (GetBookByID(id))
            {
                show(id);
                Console.WriteLine("将删除该图书记录,确认吗?(Y/N)");
                if (Console.ReadLine().ToLower().Trim().Equals("y")) {
                    if (DeleteBookByID(id) > 0)
                    {
                        Console.WriteLine("修改成功");
                    }
                    else
                    {
                        Console.WriteLine("修改失败");
                    }
                }
                else
                {
                    Console.WriteLine("未删除,返回");
                }
            }
            else
            {
                Console.WriteLine("编号不存在,重新输入");
                return;
            }
        }
        public void show(int id) {
            SqlConnection conn = new SqlConnection(connString);
            try
            {
                String s = "select book.id,book.name,booktype.typename,book.number,book.price from book,booktype where book.typle=booktype.typle and book.id="+id;
                Console.WriteLine("------------------------------------------------");
                Console.WriteLine("编号\t名称\t\t类别\t数量\t价格");
                Console.WriteLine("------------------------------------------------");
                SqlCommand comm = new SqlCommand(s, conn);
                conn.Open();
                SqlDataReader rd = comm.ExecuteReader();
                while (rd.Read())
                {
                    Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", rd["id"], rd["name"], rd["typename"], rd["number"], rd["price"]);//前面不能加" . "
                }
                rd.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
 
            }
            finally
            {
                conn.Close();
            }
        }
        public int DeleteBookByID(int id) {
            SqlConnection conn = new SqlConnection(connString);
            String s = "Delete from book where id=" + id;
            SqlCommand comm = new SqlCommand(s, conn);
            try
            {
                conn.Open();
                return comm.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return -1;
            }
            finally
            {
                conn.Close();
            }
        }

使用ADO.NET查询和操作数据的更多相关文章

  1. 使用ADO.NET 查询和操作数据

    一.使用StringBuilder类追加和删除字符串 1.创建StringBuilder类的对象 StringBuilder sb=new StringBuilder("初始字符串值&quo ...

  2. C++ ADO 数据查询

    ADO 数据查询 关键点 上1条 下1条 第1条 最后1条 实现过程 // stdafx.h : include file for standard system include files, #im ...

  3. 使用ADO.NET查询和访问数据库

    使用ADO.NET查询和访问数据库步骤 使用ADO.NET查询和访问数据库 连接数据库操作: 1.       定义连接字符串: String connString = "Data Sour ...

  4. 为什么数据可以从pl/sql查出来而使用ado.net查询,结果却是空?

    1.背景 一条记录(如select * from A where a='1'),使用pl/sql作为条件可以查询出记录,但用ado.net sql查询结果却是空. 2.原因 a字段的数据类型的char ...

  5. 一个Entity Framework、ADO.NET查询性能测试

    Entity Framework自然是会比ADO.NET性能慢点,这个不多说了.直接上结果. 本该用测试项目的,不过我建了个aspx.下面是随便测20遍得到的结果 补充!!把12行改成 list = ...

  6. ADO异步查询显示进度条

    一般,ADO都是以同步的方式来处理数据.这就是说,当ADO开始处理数据后,应用程序必须等到ADO处理完毕之后才可以继续执行.但是除了同步执行方式之外,ADO也提供了异步执行的方式,允许当ADO处理时, ...

  7. 一行code实现ADO.NET查询结果映射至实体对象。

    AutoMapper是一个.NET的对象映射工具. 主要用途 领域对象与DTO之间的转换.数据库查询结果映射至实体对象. 这次我们说说 数据库查询结果映射至实体对象. 先贴一段代码: public S ...

  8. 使用ADO.NET查询和操作数据库

    String和StringBuilder 语法: //声明一个空的StringBuilder对象 StingBuilder对象名称 = new   StringBuilder(); //声明一个Str ...

  9. Ado.Net查询语句使用临时表做条件

    using System; using System.Data; using System.Data.SqlClient; using System.Text; namespace WindowsFo ...

随机推荐

  1. ios学习笔记(一)Windows7上使用VMWare搭建iPhone开发环境

    我们都知道开发iPhone等ios平台的移动应用时需要使用Mac本,但是Mac本都比较昂贵,所以我们可以采用Windows7上利用VMWare安装Mac操作系统的方法来模拟ios开发环境,达到降低成本 ...

  2. NetBeans部署项目(Extjs)报错(二)

    NetBeans部署项目(Extjs)报错(二) 1.具体错误如下: Using CATALINA_BASE: "C:\Users\Administrator.FOXB2MKB3RGUNIL ...

  3. OTG驱动分析(一)

    前一段时间弄了2个礼拜的OTG驱动调试,感觉精神疲惫啊.主要原因还是自己对OTG功能不了解造成的.现在终于完成但是对实质原理还有些模糊.所以自己重新总结一下.因为自己是菜鸟,所以用菜鸟的白话方式分析. ...

  4. ZigBee技术

    ZigBee技术是一种近距离.低复杂度.低功耗.低速率.低成本的双向无线通讯技术.主要用于距离短.功耗低且传输速率不高的各种电子设备之间进行数据传输以及典型的有周期性数据.间歇性数据和低反应时间数据传 ...

  5. Hibernate【映射】知识要点

    前言 前面的我们使用的是一个表的操作,但我们实际的开发中不可能只使用一个表的...因此,本博文主要讲解关联映射 集合映射 需求分析:当用户购买商品,用户可能有多个地址. 数据库表 我们一般如下图一样设 ...

  6. 校园网IPv6加速

    对于广大学生来说,上网是一件很纠结的事情,校园网要么按时间计费,要么按流量计费,要么是校园宽带.按时间计费速度慢,按流量计费费用高,校园宽带还不能共享,只能电脑开热点给手机上网.有没有既能提高网速又经 ...

  7. 小程序中点击input控件键盘弹出时placeholder文字上移

    最近做的一个小程序项目中,出现了点击input控件键盘弹出时placeholder文字上移,刚开始以为是软键盘弹出布局上移问题是传说中典型的fixed 软键盘顶起问题,因此采纳了网上搜到的" ...

  8. 编写第一个Flutter App(翻译)

    博客搬迁至http://blog.wangjiegulu.com RSS订阅:http://blog.wangjiegulu.com/feed.xml 以下代码 Github 地址:https://g ...

  9. 手机浏览网页或打开App时莫名弹出支付宝领红包界面的原因及应对措施

    自从支付宝推出扫码领红包活动后,这种模式独特的赏金机制,短时间内吸引了大量的关注,但是随之也产生了很多的问题,比由于如在赏金的驱动下,微信群里铺天盖地的红包口令,朋友圈里各式各样的领红包二维码图片, ...

  10. 【网络流24题】最长k可重区间集(费用流)

    [网络流24题]最长k可重区间集(费用流) 题面 Cogs Loj 洛谷 题解 首先注意一下 这道题目里面 在Cogs上直接做就行了 洛谷和Loj上需要判断数据合法,如果\(l>r\)就要交换\ ...