连接:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. // 引入数据库管理控件
  7. using System.Data;
  8. using System.Data.SqlClient;
  9.  
  10. namespace ConsoleApplication3
  11. {
  12. class Program
  13. {
  14. static void Main(string[] args)
  15. {
  16. SqlConnection conn = new SqlConnection(); // 初始化一个SqlConnection()类
  17. conn.ConnectionString = "server=NAMEJR-PC;database=pc_test;uid=sa;pwd=****"; // 连接字符串,格式(注意间隔要使用分号(";")来做分割):"server=数据库名称(据说可以使用"."来表示本地数据库,没试过);database=数据库;uid=账号;pwd=密码"。注:如果使用的是"."进行登陆的话,可以将uid和pwd换成"integrated security=SSPI"即:"server=.;database=数据库名;integrated security=SSPI";
  18. conn.Open(); // 打开数据库
  19. SqlCommand comm = new SqlCommand(); // 初始化SqlCommand()类
  20. comm.Connection = conn; // 获取连接指针
  21. comm.CommandType = CommandType.Text; // 执行的方式,表示以SQL方式执行,另外还有CommandType.StoredProcedure(存储进程方式)。这个在"https://www.cnblogs.com/namejr/p/10398433.html"再讲。
  22. comm.CommandText = "select * from student;"; // SQL命令
  23. SqlDataReader dr = comm.ExecuteReader(); // 生成SqlDataReader
  24. dr.Close(); // 关闭SqlDataReader对象
  25. conn.Close(); // 关闭数据库连接
  26. }
  27. }
  28. }
  1. // 判断其状态是否处于关闭状态
  2. if (coon.State != ConnectionState.Closed)
  3. {
  4. coon.Close();
  5. Console.WriteLine("成功关闭!");
  6. }

Connection

使用web.config存放公共信息,有两种方式:1.appsettings。2.connectionstrings

1.使用appsettings:

  1. Web.config
  2. <?xml version="1.0" encoding="utf-8"?>
  3. <!--
  4. 有关如何配置 ASP.NET 应用程序的详细信息,请访问
  5. http://go.microsoft.com/fwlink/?LinkId=169433
  6. -->
  7. <configuration>
  8. <appSettings>
  9. <add key="cn" value="server=NAMEJR-PC;database=pc_test;uid=sa;pwd=****;"/>
  10. </appSettings>
     .............
  11. </configuration>
  12. /////////////////////////////////////////////////////////////////////////////////
  13. WebForm1.aspx
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Linq;
  17. using System.Web;
  18. using System.Web.UI;
  19. using System.Web.UI.WebControls;
  20. using System.Data;
  21. using System.Data.SqlClient;
  22.  
  23. namespace WebApplication1
  24. {
  25. public partial class WebForm1 : System.Web.UI.Page
  26. {
  27. protected void Page_Load(object sender, EventArgs e)
  28. {
  29. //
  30. }
  31. protected void Button1_Click(object sender, EventArgs e)
  32. {
  33. SqlConnection conn = new SqlConnection();
  34. conn.ConnectionString = System.Web.Configuration.WebConfigurationManager.AppSettings["cn"];
  35. try
  36. {
  37. conn.Open();
  38. this.Literal1.Text = "连接数据库成功...";
  39. }catch(Exception ex)
  40. {
  41. this.Literal1.Text = ex.Message;
  42. }
  43. finally
  44. {
  45. if (conn.State != ConnectionState.Closed)
  46. {
  47. conn.Close();
  48. }
  49. }
  50. }
  51. }
  52. }

2.以connectionStrings方式:

  1. Web.Config
  2. <?xml version="1.0" encoding="utf-8"?>
  3. <!--
  4. 有关如何配置 ASP.NET 应用程序的详细信息,请访问
  5. http://go.microsoft.com/fwlink/?LinkId=169433
  6. -->
  7. <configuration>
  8. <connectionStrings>
  9. <add name="cn" connectionString="server=NAMEJR-PC;database=pc_test;uid=sa;pwd=****;" providerName="System.Data.SqlClient"/>
  10. </connectionStrings>
  11. </configuration>
  12. /////////////////////////////////////////////////////////////////////////////
  13. WebForm1.apsx
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Linq;
  17. using System.Web;
  18. using System.Web.UI;
  19. using System.Web.UI.WebControls;
  20. using System.Data;
  21. using System.Data.SqlClient;
  22.  
  23. namespace WebApplication1
  24. {
  25. public partial class WebForm1 : System.Web.UI.Page
  26. {
  27. protected void Page_Load(object sender, EventArgs e)
  28. {
  29. //
  30. }
  31. protected void Button1_Click(object sender, EventArgs e)
  32. {
  33. SqlConnection conn = new SqlConnection();
  34. conn.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["cn"].ConnectionString;
  35. try
  36. {
  37. conn.Open();
  38. this.Literal1.Text = "连接数据库成功...";
  39. }catch(Exception ex)
  40. {
  41. this.Literal1.Text = ex.Message;
  42. }
  43. finally
  44. {
  45. if (conn.State != ConnectionState.Closed)
  46. {
  47. conn.Close();
  48. }
  49. }
  50. }
  51. }
  52. }

command:

三个属性:connection、commandType、commandText

三个方法:ExecuteReader()、ExecuteScalar()、ExecuteNonQuery()

  1. ASPX
  2. <div>
  3. 姓名:<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
  4. <br />
  5. 年龄:<asp:TextBox ID="TextBoxAge" runat="server"></asp:TextBox>
  6. <br />
  7. 性别:<asp:TextBox ID="TextBoxSex" runat="server"></asp:TextBox>
  8. <br />
  9. <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><asp:Literal ID="Literal1" runat="server"></asp:Literal>
  10. <asp:GridView ID="GridView1" runat="server"></asp:GridView>
  11. </div>
  12. ////////////////////////////////////////////////////////////////////////////////////////////\
  13. CS
  14. protected void Page_Load(object sender, EventArgs e)
  15. {
  16. //
  17. }
  18. protected void Button1_Click(object sender, EventArgs e)
  19. {
  20. SqlConnection conn = new SqlConnection();
  21. conn.ConnectionString = WebConfigurationManager.ConnectionStrings["cn"].ConnectionString;
  22. try
  23. {
  24. SqlCommand comm = new SqlCommand();
  25. comm.Connection = conn;
  26. comm.CommandType = CommandType.Text;
  27. int Sex = (this.TextBoxSex.ToString() == "男") ? : ;
  28. conn.Open(); // 打开数据库
  29. // comm.CommandText = string.Format("insert into student(name,age,sex) values('{0}',{1},{2})", this.TextBoxName.Text.ToString(), this.TextBoxAge.Text.ToString(), Sex);
  30. // int columns = comm.ExecuteNonQuery(); // 返回受影响的行数
  31. // this.Literal1.Text = string.Format("连接数据库成功,插入{0}行", columns);
  32. //
  33. // comm.CommandText = "select count(*) from student";
  34. // object columns = comm.ExecuteScalar(); // 只返回一列一行的结果
  35. // this.Literal1.Text = string.Format("这个表一共有{0}行",columns);
  36. //
  37. comm.CommandText = "select name,age,sex from student";
  38. SqlDataReader dr = comm.ExecuteReader(); // 获取全部搜索出来的对象
  39. // 进行数据绑定
  40. this.GridView1.DataSource = dr;
  41. this.GridView1.DataBind();
  42. }catch(Exception ex)
  43. {
  44. this.Literal1.Text = ex.Message;
  45. }
  46. finally
  47. {
  48. if (conn.State != ConnectionState.Closed)
  49. {
  50. conn.Close();
  51. }
  52. }
  53. }

SqlDataAdapter:

先来简单介绍dataset和datatable

  1. static void Main(string[] args)
  2. {
  3. DataSet ds = new DataSet(); // 定义一个数据集
  4. DataTable dt = new DataTable(); // 定义一个数据表
  5. dt.TableName = "jr"; // 添加表名
  6. DataColumn column0 = new DataColumn(); // 定义其中一列
  7. column0.DataType = typeof(int); // 定义该列的类型
  8. column0.AllowDBNull = false; // 定义该列为非空
  9. column0.ColumnName = "ID"; // 定义列的名称
  10. dt.Columns.Add(column0); // 将该行添加到数据表
  11. DataColumn column1 = new DataColumn();
  12. column1.DataType = typeof(string);
  13. column1.ColumnName = "NAME";
  14. dt.Columns.Add(column1);
  15. // 添加数据方式1
  16. dt.Rows.Add(, "namejr"); // 添加一行
  17. // 添加数据方式2
  18. var row0 = dt.NewRow();
  19. row0[] = ; // 按下标/索引添加
  20. row0["NAME"] = "name"; // 按键添加
  21. ds.Tables.Add(dt); // 添加到数据集
  22. //
  23. // 读取数据
  24. object obj = ds.Tables[].Rows[]["NAME"];
  25. Console.WriteLine(obj);
  26. }

SqlDataAdapter

  1. using System.Data;
  2. using System.Data.SqlClient;
  3. using System.Web.Configuration;
  4.  
  5. protected void Page_Load(object sender, EventArgs e)
  6. {
  7. //
  8. }
  9.  
  10. protected void Button1_Click(object sender, EventArgs e)
  11. {
  12. /*
  13. // 简便写法:
  14. SqlDataAdapter da = new SqlDataAdapter("select name,age,sex from student", WebConfigurationManager.ConnectionStrings["cn"].ConnectionString); // 使用SqlDataAdapter不需要使用open/close打开或者关闭数据库
  15. DataSet ds = new DataSet(); // 数据缓存
  16. da.Fill(ds, "S"); // 填充。fill可以给取出来的缓存表进行取别名
  17. this.GridView1.DataSource = ds.Tables["S"];
  18. this.GridView1.DataBind();
  19. */
  20. SqlConnection conn = new SqlConnection();
  21. conn.ConnectionString = WebConfigurationManager.ConnectionStrings["cn"].ConnectionString;
  22. try
  23. {
  24. SqlCommand comm = new SqlCommand(); // 创建command
  25. comm.Connection = conn; // 获取连接配置信息
  26. comm.CommandType = CommandType.Text; // 以SQL语句方式执行
  27. comm.CommandText = "select name,age,sex from student"; // SQL语句
  28. SqlDataAdapter da = new SqlDataAdapter(); // 同上
  29. da.SelectCommand = comm; // 执行操作。此外还有InsertCommand/DeleteCommand/UpdateCommand
  30. DataSet ds = new DataSet();
  31. da.Fill(ds, "S");
  32. this.GridView1.DataSource = ds.Tables["S"];
  33. this.GridView1.DataBind();
  34. }
  35. catch(Exception err)
  36. {
  37. this.Label1.Text = err.Message;
  38. }
  39. }

ExecuteReader():只读,向前,独占连接,效率高

  1. protected void Button1_Click(object sender, EventArgs e)
  2. {
  3. SqlConnection conn = new SqlConnection();
  4. conn.ConnectionString = WebConfigurationManager.ConnectionStrings["cn"].ConnectionString;
  5. try
  6. {
  7. SqlCommand comm = new SqlCommand();
  8. comm.Connection = conn;
  9. comm.CommandType = CommandType.Text;
  10. /*
  11. // 只对一个结果集进行读取
  12. comm.CommandText = "select name,age,sex from student";
  13. conn.Open();
  14. SqlDataReader dr = comm.ExecuteReader();
  15. // dr.Read()向下读取一条数据,存在数据返回true,不存在数据返回false
  16. while (dr.Read())
  17. {
  18. // 使用下标做索引(有装箱拆箱操作)
  19. //this.TextBox1.Text += string.Format("NAME:{0}, AGE:{1}, SEX:{2}\r\n", dr[0], dr[1], dr[2]);
  20. // 使用表名做索引(有装箱拆箱操作)
  21. //this.TextBox1.Text += string.Format("NAME:{0}, AGE:{1}, SEX:{2}\r\n", dr["name"], dr["age"], dr["sex"]);
  22. //
  23. // 还有一种r.GetXXX(i),不需要进行装箱拆箱,但是必须对应其属性,例如:dr.GetInt32(1)
  24. }*/
  25. //
  26. // 对两个结果集进行操作
  27. comm.CommandText = "select name,age from student;select sex from student"; // 获取到的是两个结果集
  28. conn.Open();
  29. SqlDataReader dr = comm.ExecuteReader();
  30. while (dr.Read())
  31. {
  32. this.TextBox1.Text += string.Format("NAME:{0}, AGE:{1}\r\n", dr["name"], dr["age"]);
  33. }
  34. dr.NextResult(); // 转到下一个结果集
  35. while (dr.Read())
  36. {
  37. this.TextBox1.Text += string.Format("SEX:{0}\r\n", dr["sex"]);
  38. }
  39. }
  40. catch (Exception err)
  41. {
  42. this.Label1.Text = err.Message;
  43. }
  44. finally
  45. {
  46. if (conn.State != ConnectionState.Closed)
  47. {
  48. conn.Close();
  49. }
  50. }
  51. }

C# 数据库的更多相关文章

  1. JSP应用开发 -------- 电纸书(未完待续)

    http://www.educity.cn/jiaocheng/j9415.html JSP程序员常用的技术   第1章 JSP及其相关技术导航 [本章专家知识导学] JSP是一种编程语言,也是一种动 ...

  2. nodejs进阶(6)—连接MySQL数据库

    1. 建库连库 连接MySQL数据库需要安装支持 npm install mysql 我们需要提前安装按mysql sever端 建一个数据库mydb1 mysql> CREATE DATABA ...

  3. GreenDao 数据库:使用Raw文件夹下的数据库文件以及数据库升级

    一.使用Raw文件夹下的数据库文件 在使用GreenDao框架时,数据库和数据表都是根据生成的框架代码来自动创建的,从生成的DaoMaster中的OpenHelper类可以看出: public sta ...

  4. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库

    在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...

  5. Java MyBatis 插入数据库返回主键

    最近在搞一个电商系统中由于业务需求,需要在插入一条产品信息后返回产品Id,刚开始遇到一些坑,这里做下笔记,以防今后忘记. 类似下面这段代码一样获取插入后的主键 User user = new User ...

  6. 在SQL2008查找某数据库中的列是否存在某个值

    在SQL2008查找某数据库中的列是否存在某个值 --SQL2008查找某数据库中的列是否存在某个值 create proc spFind_Column_In_DB ( @type int,--类型: ...

  7. 分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间)

    分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间) 很多时候我们都需要计算数据库中各个表的数据量和每行记录所占用空间 这里共享一个脚本 CREATE TABLE #tab ...

  8. SQL Server2014 SP2新增的数据库克隆功能

    SQL Server2014 SP2新增的数据库克隆功能 创建测试库 --创建测试数据库 create database testtest use testtest go --创建表 )) --插入数 ...

  9. 数据库优化案例——————某市中心医院HIS系统

    记得在自己学习数据库知识的时候特别喜欢看案例,因为优化的手段是容易掌握的,但是整体的优化思想是很难学会的.这也是为什么自己特别喜欢看案例,今天也开始分享自己做的优化案例. 最近一直很忙,博客产出也少的 ...

  10. NoSql数据库使用半年后在设计上面的一些心得

    NoSql数据库这个概念听闻许久了,也陆续看到很多公司和产品都在使用,优缺点似乎都被分析的清清楚楚.但我心里一直存有一个疑惑,它的出现究竟是为了解决什么问题? 这个疑惑非常大,为此我看了很多分析文章, ...

随机推荐

  1. 《F4+2》—基于原型的团队项目需求调研与分析

    任务一 1.调研对象 老师和学生 2.所开发的软件原型 太阳系模型软件 3.调研方法 问卷调查法 原型法 任务二 采用UML模型描述任务1所获取的用户需求,如下: 主要需求: 教师:把系统展示给学生, ...

  2. Entity FrameWork 增删改查

         Entity Framework (又称ADO.NET Entity Framework) 是微软以 ADO.NET 为基础所发展出来的对象关系对应(O/R Mapping) 解决方案   ...

  3. vue中插入Echarts示例(菜鸟记录)

  4. mockjs学习

    mockjs简单学习与应用,可以满足工作所需就行.*************************************************************************** ...

  5. guxh的python笔记七:抽象基类

    1,鸭子类型和白鹅类型 1.1,白鹅类型 白鹅类型对接口有明确定义,比如不可变序列(Sequence),需要实现__contains__,__iter__,__len__,__getitem__,__ ...

  6. Otto.de:我为什么选择分布式垂直架构

    Otto.de:我为什么选择分布式垂直架构 http://cloud.51cto.com/art/201510/493867.htm

  7. Linux(CentOS 7)命令行模式安装VMware Tools 详解

    本篇文章主要介绍了如何在Linux(CentOS 7)命令行模式安装VMware Tools,具有一定的参考价值,感兴趣的小伙伴们可以参考一下. 本例中为在Linux(以CentOS 7为例)安装VM ...

  8. idea中springboot项目程序入口右键不显示run as的原因

    今天在idea中导入了springboot的项目,但是在程序的入口处右键单击没有出现run  as 的程序启动方式,主要原因在于idea中右面的maven projects中没加载项目,需要点击“+“ ...

  9. 解决SpringMVC+Thymeleaf中文乱码

    乱码效果截图 解决办法:在org.thymeleaf.templateresolver.ServletContextTemplateResolver和org.thymeleaf.spring5.vie ...

  10. css清除常用默认样式表

    /*公共样式*/ html, body, div, ul, li, h1, h2, h3, h4, h5, h6, p, dl, dt, dd, ol, form, input, textarea, ...