C# 数据库
连接:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- // 引入数据库管理控件
- using System.Data;
- using System.Data.SqlClient;
- namespace ConsoleApplication3
- {
- class Program
- {
- static void Main(string[] args)
- {
- SqlConnection conn = new SqlConnection(); // 初始化一个SqlConnection()类
- 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";
- conn.Open(); // 打开数据库
- SqlCommand comm = new SqlCommand(); // 初始化SqlCommand()类
- comm.Connection = conn; // 获取连接指针
- comm.CommandType = CommandType.Text; // 执行的方式,表示以SQL方式执行,另外还有CommandType.StoredProcedure(存储进程方式)。这个在"https://www.cnblogs.com/namejr/p/10398433.html"再讲。
- comm.CommandText = "select * from student;"; // SQL命令
- SqlDataReader dr = comm.ExecuteReader(); // 生成SqlDataReader
- dr.Close(); // 关闭SqlDataReader对象
- conn.Close(); // 关闭数据库连接
- }
- }
- }
- // 判断其状态是否处于关闭状态
- if (coon.State != ConnectionState.Closed)
- {
- coon.Close();
- Console.WriteLine("成功关闭!");
- }
Connection
使用web.config存放公共信息,有两种方式:1.appsettings。2.connectionstrings
1.使用appsettings:
- Web.config:
- <?xml version="1.0" encoding="utf-8"?>
- <!--
- 有关如何配置 ASP.NET 应用程序的详细信息,请访问
- http://go.microsoft.com/fwlink/?LinkId=169433
- -->
- <configuration>
- <appSettings>
- <add key="cn" value="server=NAMEJR-PC;database=pc_test;uid=sa;pwd=****;"/>
- </appSettings>
.............- </configuration>
- /////////////////////////////////////////////////////////////////////////////////
- WebForm1.aspx:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- namespace WebApplication1
- {
- public partial class WebForm1 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- //
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- SqlConnection conn = new SqlConnection();
- conn.ConnectionString = System.Web.Configuration.WebConfigurationManager.AppSettings["cn"];
- try
- {
- conn.Open();
- this.Literal1.Text = "连接数据库成功...";
- }catch(Exception ex)
- {
- this.Literal1.Text = ex.Message;
- }
- finally
- {
- if (conn.State != ConnectionState.Closed)
- {
- conn.Close();
- }
- }
- }
- }
- }
2.以connectionStrings方式:
- Web.Config:
- <?xml version="1.0" encoding="utf-8"?>
- <!--
- 有关如何配置 ASP.NET 应用程序的详细信息,请访问
- http://go.microsoft.com/fwlink/?LinkId=169433
- -->
- <configuration>
- <connectionStrings>
- <add name="cn" connectionString="server=NAMEJR-PC;database=pc_test;uid=sa;pwd=****;" providerName="System.Data.SqlClient"/>
- </connectionStrings>
- </configuration>
- /////////////////////////////////////////////////////////////////////////////
- WebForm1.apsx:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- namespace WebApplication1
- {
- public partial class WebForm1 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- //
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- SqlConnection conn = new SqlConnection();
- conn.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["cn"].ConnectionString;
- try
- {
- conn.Open();
- this.Literal1.Text = "连接数据库成功...";
- }catch(Exception ex)
- {
- this.Literal1.Text = ex.Message;
- }
- finally
- {
- if (conn.State != ConnectionState.Closed)
- {
- conn.Close();
- }
- }
- }
- }
- }
command:
三个属性:connection、commandType、commandText
三个方法:ExecuteReader()、ExecuteScalar()、ExecuteNonQuery()
- ASPX:
- <div>
- 姓名:<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
- <br />
- 年龄:<asp:TextBox ID="TextBoxAge" runat="server"></asp:TextBox>
- <br />
- 性别:<asp:TextBox ID="TextBoxSex" runat="server"></asp:TextBox>
- <br />
- <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><asp:Literal ID="Literal1" runat="server"></asp:Literal>
- <asp:GridView ID="GridView1" runat="server"></asp:GridView>
- </div>
- ////////////////////////////////////////////////////////////////////////////////////////////\
- CS:
- protected void Page_Load(object sender, EventArgs e)
- {
- //
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- SqlConnection conn = new SqlConnection();
- conn.ConnectionString = WebConfigurationManager.ConnectionStrings["cn"].ConnectionString;
- try
- {
- SqlCommand comm = new SqlCommand();
- comm.Connection = conn;
- comm.CommandType = CommandType.Text;
- int Sex = (this.TextBoxSex.ToString() == "男") ? : ;
- conn.Open(); // 打开数据库
- // comm.CommandText = string.Format("insert into student(name,age,sex) values('{0}',{1},{2})", this.TextBoxName.Text.ToString(), this.TextBoxAge.Text.ToString(), Sex);
- // int columns = comm.ExecuteNonQuery(); // 返回受影响的行数
- // this.Literal1.Text = string.Format("连接数据库成功,插入{0}行", columns);
- //
- // comm.CommandText = "select count(*) from student";
- // object columns = comm.ExecuteScalar(); // 只返回一列一行的结果
- // this.Literal1.Text = string.Format("这个表一共有{0}行",columns);
- //
- comm.CommandText = "select name,age,sex from student";
- SqlDataReader dr = comm.ExecuteReader(); // 获取全部搜索出来的对象
- // 进行数据绑定
- this.GridView1.DataSource = dr;
- this.GridView1.DataBind();
- }catch(Exception ex)
- {
- this.Literal1.Text = ex.Message;
- }
- finally
- {
- if (conn.State != ConnectionState.Closed)
- {
- conn.Close();
- }
- }
- }
SqlDataAdapter:
先来简单介绍dataset和datatable
- static void Main(string[] args)
- {
- DataSet ds = new DataSet(); // 定义一个数据集
- DataTable dt = new DataTable(); // 定义一个数据表
- dt.TableName = "jr"; // 添加表名
- DataColumn column0 = new DataColumn(); // 定义其中一列
- column0.DataType = typeof(int); // 定义该列的类型
- column0.AllowDBNull = false; // 定义该列为非空
- column0.ColumnName = "ID"; // 定义列的名称
- dt.Columns.Add(column0); // 将该行添加到数据表
- DataColumn column1 = new DataColumn();
- column1.DataType = typeof(string);
- column1.ColumnName = "NAME";
- dt.Columns.Add(column1);
- // 添加数据方式1
- dt.Rows.Add(, "namejr"); // 添加一行
- // 添加数据方式2
- var row0 = dt.NewRow();
- row0[] = ; // 按下标/索引添加
- row0["NAME"] = "name"; // 按键添加
- ds.Tables.Add(dt); // 添加到数据集
- //
- // 读取数据
- object obj = ds.Tables[].Rows[]["NAME"];
- Console.WriteLine(obj);
- }
SqlDataAdapter
- using System.Data;
- using System.Data.SqlClient;
- using System.Web.Configuration;
- protected void Page_Load(object sender, EventArgs e)
- {
- //
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- /*
- // 简便写法:
- SqlDataAdapter da = new SqlDataAdapter("select name,age,sex from student", WebConfigurationManager.ConnectionStrings["cn"].ConnectionString); // 使用SqlDataAdapter不需要使用open/close打开或者关闭数据库
- DataSet ds = new DataSet(); // 数据缓存
- da.Fill(ds, "S"); // 填充。fill可以给取出来的缓存表进行取别名
- this.GridView1.DataSource = ds.Tables["S"];
- this.GridView1.DataBind();
- */
- SqlConnection conn = new SqlConnection();
- conn.ConnectionString = WebConfigurationManager.ConnectionStrings["cn"].ConnectionString;
- try
- {
- SqlCommand comm = new SqlCommand(); // 创建command
- comm.Connection = conn; // 获取连接配置信息
- comm.CommandType = CommandType.Text; // 以SQL语句方式执行
- comm.CommandText = "select name,age,sex from student"; // SQL语句
- SqlDataAdapter da = new SqlDataAdapter(); // 同上
- da.SelectCommand = comm; // 执行操作。此外还有InsertCommand/DeleteCommand/UpdateCommand
- DataSet ds = new DataSet();
- da.Fill(ds, "S");
- this.GridView1.DataSource = ds.Tables["S"];
- this.GridView1.DataBind();
- }
- catch(Exception err)
- {
- this.Label1.Text = err.Message;
- }
- }
ExecuteReader():只读,向前,独占连接,效率高
- protected void Button1_Click(object sender, EventArgs e)
- {
- SqlConnection conn = new SqlConnection();
- conn.ConnectionString = WebConfigurationManager.ConnectionStrings["cn"].ConnectionString;
- try
- {
- SqlCommand comm = new SqlCommand();
- comm.Connection = conn;
- comm.CommandType = CommandType.Text;
- /*
- // 只对一个结果集进行读取
- comm.CommandText = "select name,age,sex from student";
- conn.Open();
- SqlDataReader dr = comm.ExecuteReader();
- // dr.Read()向下读取一条数据,存在数据返回true,不存在数据返回false
- while (dr.Read())
- {
- // 使用下标做索引(有装箱拆箱操作)
- //this.TextBox1.Text += string.Format("NAME:{0}, AGE:{1}, SEX:{2}\r\n", dr[0], dr[1], dr[2]);
- // 使用表名做索引(有装箱拆箱操作)
- //this.TextBox1.Text += string.Format("NAME:{0}, AGE:{1}, SEX:{2}\r\n", dr["name"], dr["age"], dr["sex"]);
- //
- // 还有一种r.GetXXX(i),不需要进行装箱拆箱,但是必须对应其属性,例如:dr.GetInt32(1)
- }*/
- //
- // 对两个结果集进行操作
- comm.CommandText = "select name,age from student;select sex from student"; // 获取到的是两个结果集
- conn.Open();
- SqlDataReader dr = comm.ExecuteReader();
- while (dr.Read())
- {
- this.TextBox1.Text += string.Format("NAME:{0}, AGE:{1}\r\n", dr["name"], dr["age"]);
- }
- dr.NextResult(); // 转到下一个结果集
- while (dr.Read())
- {
- this.TextBox1.Text += string.Format("SEX:{0}\r\n", dr["sex"]);
- }
- }
- catch (Exception err)
- {
- this.Label1.Text = err.Message;
- }
- finally
- {
- if (conn.State != ConnectionState.Closed)
- {
- conn.Close();
- }
- }
- }
C# 数据库的更多相关文章
- JSP应用开发 -------- 电纸书(未完待续)
http://www.educity.cn/jiaocheng/j9415.html JSP程序员常用的技术 第1章 JSP及其相关技术导航 [本章专家知识导学] JSP是一种编程语言,也是一种动 ...
- nodejs进阶(6)—连接MySQL数据库
1. 建库连库 连接MySQL数据库需要安装支持 npm install mysql 我们需要提前安装按mysql sever端 建一个数据库mydb1 mysql> CREATE DATABA ...
- GreenDao 数据库:使用Raw文件夹下的数据库文件以及数据库升级
一.使用Raw文件夹下的数据库文件 在使用GreenDao框架时,数据库和数据表都是根据生成的框架代码来自动创建的,从生成的DaoMaster中的OpenHelper类可以看出: public sta ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库
在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...
- Java MyBatis 插入数据库返回主键
最近在搞一个电商系统中由于业务需求,需要在插入一条产品信息后返回产品Id,刚开始遇到一些坑,这里做下笔记,以防今后忘记. 类似下面这段代码一样获取插入后的主键 User user = new User ...
- 在SQL2008查找某数据库中的列是否存在某个值
在SQL2008查找某数据库中的列是否存在某个值 --SQL2008查找某数据库中的列是否存在某个值 create proc spFind_Column_In_DB ( @type int,--类型: ...
- 分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间)
分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间) 很多时候我们都需要计算数据库中各个表的数据量和每行记录所占用空间 这里共享一个脚本 CREATE TABLE #tab ...
- SQL Server2014 SP2新增的数据库克隆功能
SQL Server2014 SP2新增的数据库克隆功能 创建测试库 --创建测试数据库 create database testtest use testtest go --创建表 )) --插入数 ...
- 数据库优化案例——————某市中心医院HIS系统
记得在自己学习数据库知识的时候特别喜欢看案例,因为优化的手段是容易掌握的,但是整体的优化思想是很难学会的.这也是为什么自己特别喜欢看案例,今天也开始分享自己做的优化案例. 最近一直很忙,博客产出也少的 ...
- NoSql数据库使用半年后在设计上面的一些心得
NoSql数据库这个概念听闻许久了,也陆续看到很多公司和产品都在使用,优缺点似乎都被分析的清清楚楚.但我心里一直存有一个疑惑,它的出现究竟是为了解决什么问题? 这个疑惑非常大,为此我看了很多分析文章, ...
随机推荐
- 《F4+2》—基于原型的团队项目需求调研与分析
任务一 1.调研对象 老师和学生 2.所开发的软件原型 太阳系模型软件 3.调研方法 问卷调查法 原型法 任务二 采用UML模型描述任务1所获取的用户需求,如下: 主要需求: 教师:把系统展示给学生, ...
- Entity FrameWork 增删改查
Entity Framework (又称ADO.NET Entity Framework) 是微软以 ADO.NET 为基础所发展出来的对象关系对应(O/R Mapping) 解决方案 ...
- vue中插入Echarts示例(菜鸟记录)
- mockjs学习
mockjs简单学习与应用,可以满足工作所需就行.*************************************************************************** ...
- guxh的python笔记七:抽象基类
1,鸭子类型和白鹅类型 1.1,白鹅类型 白鹅类型对接口有明确定义,比如不可变序列(Sequence),需要实现__contains__,__iter__,__len__,__getitem__,__ ...
- Otto.de:我为什么选择分布式垂直架构
Otto.de:我为什么选择分布式垂直架构 http://cloud.51cto.com/art/201510/493867.htm
- Linux(CentOS 7)命令行模式安装VMware Tools 详解
本篇文章主要介绍了如何在Linux(CentOS 7)命令行模式安装VMware Tools,具有一定的参考价值,感兴趣的小伙伴们可以参考一下. 本例中为在Linux(以CentOS 7为例)安装VM ...
- idea中springboot项目程序入口右键不显示run as的原因
今天在idea中导入了springboot的项目,但是在程序的入口处右键单击没有出现run as 的程序启动方式,主要原因在于idea中右面的maven projects中没加载项目,需要点击“+“ ...
- 解决SpringMVC+Thymeleaf中文乱码
乱码效果截图 解决办法:在org.thymeleaf.templateresolver.ServletContextTemplateResolver和org.thymeleaf.spring5.vie ...
- css清除常用默认样式表
/*公共样式*/ html, body, div, ul, li, h1, h2, h3, h4, h5, h6, p, dl, dt, dd, ol, form, input, textarea, ...