连接:

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# 数据库的更多相关文章

  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. backbone点滴

    可以查看http://www.css88.com/doc/backbone/ backbone与angular http://www.infoq.com/cn/articles/backbone-vs ...

  2. (18)ProcessPoolExecutor进程池

    # 新版本的进程池 ProcessPoolExecutor # 实例化进程池 ProcessPoolExcutor(cpu_count) # 异步提交任务 submit / map # 阻塞直到任务完 ...

  3. ES6 新加的类型Symbol()

    Symbol()如果一个对象中的键已经存在,但目前我们目前不知道这个键是存在的,然后我们去给这个键赋值,Symbol()就不会改变这个键对应的值

  4. 完整的Django入门指南学习笔记5

    前言 欢迎来到本系列教程的第5部分,在这节课,我们将学习如何保护视图防止未登录的用户访问,以及在视图和表单中访问已经登录的用户,我们还将实现主题列表和回复列表视图,最后,将探索Django ORM的一 ...

  5. day15_python_1124

    03序列化模块 04加密模块 05 os sys 模块 06 collections 模块 # 03 序列化模块 # 网络传输数据:字节 bytes# 文件写入内容:bytes , str # dic ...

  6. linux下mysql多实例安装

    1.MySQL多实例介绍 1.1.什么是MySQL多实例 MySQL多实例就是在一台机器上开启多个不同的服务端口(如:3306,3307),运行多个MySQL服务进程,通过不同的socket监听不同的 ...

  7. VSTO:使用C#开发Excel、Word【17】

    使用Range对象Range对象表示电子表格中的单元格范围.范围可以包含一个单元格,多个连续的单元格,甚至多个不连续的单元格.您可以在Excel中选择时按住Ctrl键选择多个不连续的单元格. 获取特定 ...

  8. python笔记17-全局变量、局部变量

    在函数里面定义变量叫局部变量,它只能在函数里面用出了该函数外,就不能使用了在函数外面定义的变量,是全局变量,在函数内也可以使用 如果想在函数里面修改全局变量的值,那么要先用global关键字声明 要修 ...

  9. My SQL随记 002 登陆

    如何启动MySQL服务 Step1 我的电脑右键属性找到 控制面板 选择 系统和安全 Step2 管理工具中找到服务 Step3 找到你的MySQL启动服务 如何通过黑窗口登陆退出 MySQL Ste ...

  10. activity select problem(greedy algorithms)

    many activities will use the same place, every activity ai has its'  start time si and finish time f ...