18-数据库开发及ado.net

连接数据库...改向表中插入数据并且返回自动编号.SQLDataReade读取数据

ADO.NET

为什么要学习?

我们要搭建一个平台(Web/Winform)让用户方便的操作数据库中的数据。

什么是ADO.NET

是一组库类,System.Data.

Ado.net组成

Connection:用来连接数据库

Command:用来执行SQL语句

DataReader:只读、只进的结果集,一条一条读取数据(SteamReader、XmlReader)

DataAdapter:一个封装了上面3个对象的对象。

数据集(DataSet),临时数据库。

断开式数据操作

Ado.net 中其它常见类

ConnectionStringBuilder  --自动生成连接字符串

Parameter  --带参数的SQL语句

Transaction  --在ADO.NET中使用事务

与DataSet相关的类

DataView ---视图类,DataTable 中的数据以不同的视角查看

DataRowView --- DataView的行

DataTable ---DataSet中的数据表

DataRow --- DataTable中的行

DataColumn --- DataTable中的列

DataRealation --- DataTable与DataTable的关系

Contraint ---DataTable中建立的约束

#region 通过ado.net连接数据库

//1.编写连接字符串

string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

//string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Persist Security Info=True;User ID=sa";

//使用windows身份验证方式

//string constr="Data Source=127.0.0.1\BLEACHMSSQL;Initial Catalog=itcast2013;Integrated Security=true";

//2.创建连接对象

SqlConnection con = new SqlConnection(constr);

//3.打开连接

con.Open ();

Console.WriteLine ("使用连接对象");

//4.关闭连接

con.Close ();

//5.释放资源

con.Dispose ();

Console .WriteLine ("连接关闭,并释放资源");

Console .WriteLine ("OK");

Console .ReadKey ();

#endregion

//另外一种连接方式

string constr1 = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;Integrated Security=true";

using (SqlConnection con1 = new SqlConnection(constr1))

{

//con1.Open();

}

Console.ReadKey();

//第一个对象Connection

//1.数据库不可以重复打开

string constr2 = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

using (SqlConnection  con2=new SqlConnection (constr2))

{

con2.Open();

Console.WriteLine("第一次打开数据库连接");

/////数据库不可以重复打开

// con2.Open();

// Console.WriteLine("第二次打开数据库连接");

//判断数据库是否已打开

if (con2.State == System.Data.ConnectionState.Closed)//ConnectionState枚举

{

con2.Open();//如果当前数据库已经关闭,则再次打开。

}

con.Close();//关闭连接,相当于设置障碍

con.Dispose();//相当于把路拆了,这块地可以盖楼了。

Console.ReadKey();

}

/// <summary>

/// 添加操作

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void button1_Click(object sender, EventArgs e)

{

//向TblPerson表中插入一条记录

//1.连接数据库

//连接字符串

string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

//创建连接对象

using (SqlConnection con=new SqlConnection (constr) )

{

//打开数据库连接

//如果con对象是其它地方传递过来的一个对象,则在打开前最好判断con.State

con.Open();

//向表中插入一条数据

//先构建一个sql语句

string sql = string.Format("insert into TblPerson(uname,uage,uheight) values('{0}','{1}','{2}')", "黄林", 18, 175);

//执行sql语句需要一个“命令对象”

//创建一个命令对象

using (SqlCommand cmd=new SqlCommand (sql,con))

{

#region SqlCommand对象常用的三个方法

//执行sql语句

//当执行 insert,delete,update语句时,一般使用该方法

//cmd.ExecuteNonQuery()

//当执行返回单个值的SQL语句时使用该方法

//cmd.ExecuteScalar()

//当执行sql语句返回多行多列时候,一般使用该方法。查询。

//cmd.ExecuteReader ()

#endregion

//这里要执行insert语句所以用ExecuteNonQuery()方法

//通过调用该方法就会将insert语句交给数据库引擎来执行

//这个方法的返回值是一个Int类型,表示当前Sql语句执行后所影响的行数

int r = cmd.ExecuteNonQuery();

con.Close();

Console.WriteLine("成功插入{0}行", r);

}

}

}

/// <summary>

/// //删除操作

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void button2_Click(object sender, EventArgs e)

{

//删除操作

string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

string sql = string.Format("delete from TblPerson where autoId={0}",19);

using (SqlConnection con = new SqlConnection(constr))

{

using (SqlCommand cmd=new SqlCommand (sql,con))

{

//尽可能晚的开启

con.Open();

int r= cmd.ExecuteNonQuery();

//使用完毕尽可能早的关闭连接

con.Close();

Console.WriteLine("成功删除{0}行", r);

}

}

MessageBox.Show("Ok");

}

/// <summary>

/// 更新操作

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void button3_Click(object sender, EventArgs e)

{

//更新操作

string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

string sql = string.Format("update  TblPerson set uname='{0}'  where autoId={1}", "许正龙",40);

using (SqlConnection con = new SqlConnection(constr))

{

using (SqlCommand cmd = new SqlCommand(sql, con))

{

//尽可能晚的开启

con.Open();

int r = cmd.ExecuteNonQuery();

//使用完毕尽可能早的关闭连接

con.Close();

Console.WriteLine("成功更新{0}行", r);

}

}

MessageBox.Show("Ok");

}

异常处理

可以使用try…catch…finally 来捕获异常

/// <summary>

/// 查询及异常处理方法

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void button4_Click(object sender, EventArgs e)

{

//显示表中的记录的条数

string constr = "Data Source=127.0.0.1\\BLEACHMSSQL1;Initial Catalog=itcast2013;user=sa;Password=root";

string sql = "select count(*) from TblClass";

int r = 0;

try

{

using (SqlConnection con = new SqlConnection(constr))

{

using (SqlCommand cmd = new SqlCommand(sql, con))

{

try

{

con.Open();

r = Convert.ToInt32(cmd.ExecuteScalar());

con.Close();

//Console.WriteLine("成功更新{0}行", r);

}

catch (Exception ex1)

{

Console.WriteLine("发生了异常:" + ex1.Message);

}

finally

{

con.Close();

con.Dispose();

}

}

}

}

catch (Exception ex)

{

Console.WriteLine("发生了异常:"+ex.Message );

}

MessageBox.Show("表中有"+ r +"条记录");

}

ConnectionStringBuilder类演示

private void button1_Click(object sender, EventArgs e)

{

SqlConnectionStringBuilder connStrbuilder = new SqlConnectionStringBuilder();

connStrbuilder.DataSource = "127.0.0.1\\BLEACHMSSQL";

connStrbuilder.InitialCatalog = "itcast2013";

connStrbuilder.IntegratedSecurity = true;

connStrbuilder.Pooling = true;

MessageBox.Show(connStrbuilder.ConnectionString);

}

private void Form1_Load(object sender, EventArgs e)

{

SqlConnectionStringBuilder connStrbuilder = new SqlConnectionStringBuilder();

propertyGrid1.SelectedObject = connStrbuilder;

}

/// <summary>

/// 向表中插入数据,返回自动编号

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void button5_Click(object sender, EventArgs e)

{

//连接字符串

string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

string sql = string .Format ("insert into TblClass output inserted.tClassId values('{0}','{1}')",textBox1 .Text .Trim (),textBox2 .Text .Trim());

//其中,inserted 是一个触发器

int tclassId = -1;

using (SqlConnection  con=new SqlConnection (constr))

{

using (SqlCommand cmd=new SqlCommand (sql,con))

{

cmd.StatementCompleted += new StatementCompletedEventHandler(cmd_Statementcompleted);

con.Open();

tclassId =Convert.ToInt32 ( cmd.ExecuteScalar());

con.Close();

}

}

MessageBox.Show("成功插入,主键ID为:"+ tclassId +"");

}

private void cmd_Statementcompleted(object sender, StatementCompletedEventArgs e)

{

//输出每条Sql语句执行所影响的行数。

throw new NotImplementedException();

}

查询表中的所有记录

#region 将TblPerson表中的数据输出到控制台

string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

string sql = "select * from TblPerson";

using (SqlConnection con=new SqlConnection (constr))

{

using (SqlCommand cmd=new SqlCommand (sql,con))

{

con.Open();

using (SqlDataReader reader = cmd.ExecuteReader())

{

//判断当前的reader是否读取到了数据

if (reader .HasRows)

{

///通过列名来获取列的值,将索引写在循环外面,提高效率[建议使用该方式]

int autoIdIndex=reader .GetOrdinal ("autoId");

int unameIndex = reader.GetOrdinal("uname");

int uageIndex = reader.GetOrdinal("uage");

int uheightIndex = reader.GetOrdinal("uheight");

//循环读取每一条数据

while (reader .Read ())

{

#region 通过SqlDataReader的索引器和GetValue()方法获取列值

//通过reader获取行中列的方法一。

//通过reader的所引起可以使用列索引,也可以使用列名。reader["列名"];(性能比较高)

//强烈建议使用列索引,如果必须要使用列名,也要使用列索引。

//读取当前行中的每一列的数据

object obj1 = reader[0];

object obj2 = reader[1];

object obj3 = reader[2];

object obj4 = reader[3];

Console.WriteLine("{0}\t{1}\t{2}\t{3}\t", obj1, obj2, obj3, obj4);

//通过reader获取行中列的方法二。

//reader.GetValue()不支持列名,只支持列索引

object obj5 = reader.GetValue(0);

object obj6 = reader.GetValue(1);

object obj7 = reader.GetValue(2);

object obj8 = reader.GetValue(3);

//this.GetOrdinal(name);根据列名获取列的索引。

#endregion

#region 通过reader获取列值的时候,使用强类型

//autoId, uname, uage, uheight

//当使用强类型的时候,如果数据库中的值为null,则报错。

//避免方式:判断是否为null即可。

int autoId = reader.GetInt32(0);

string name = reader.GetString(1);

//int?表示可空值类型,

int? uage = reader.IsDBNull(2) ?null :(int?) reader.GetInt32(2);

int? height = reader.IsDBNull(3) ? null : (int?)reader.GetInt32(3);

Console.WriteLine("{0}\t{1}\t{2}\t{3}\t", autoId, name, uage, height);

#endregion

#region 通过列名来获取列的值[建议使用该方式]

Console.WriteLine("{0}\t{1}\t{2}\t{3}\t",

reader.GetInt32(autoIdIndex),

reader.GetString(unameIndex),

reader.GetInt32(uageIndex),

reader.GetInt32(uheightIndex));

#endregion

}

}

}

}

}

Console.WriteLine("OK");

Console.ReadKey();

#endregion

}

把表中的数据绑定到控件上

#region 将TblPerson表中的数据输出到控制台

string constr = "Data Source=127.0.0.1\\BLEACHMSSQL;Initial Catalog=itcast2013;user=sa;Password=root";

string sql = "select * from TblPerson";

List <Person> list=new List<Person>();

using (SqlConnection con = new SqlConnection(constr))

{

using (SqlCommand cmd = new SqlCommand(sql, con))

{

con.Open();

using (SqlDataReader reader = cmd.ExecuteReader())

{

//判断当前的reader是否读取到了数据

if (reader.HasRows)

{

///通过列名来获取列的值,将索引写在循环外面,提高效率[建议使用该方式]

int autoIdIndex = reader.GetOrdinal("autoId");

int unameIndex = reader.GetOrdinal("uname");

int uageIndex = reader.GetOrdinal("uage");

int uheightIndex = reader.GetOrdinal("uheight");

//循环读取每一条数据

while (reader.Read())

{

#region 通过列名来获取列的值[建议使用该方式]

//Console.WriteLine("{0}\t{1}\t{2}\t{3}\t",

//    reader.GetInt32(autoIdIndex),

//    reader.GetString(unameIndex),

//    reader.GetInt32(uageIndex),

//    reader.GetInt32(uheightIndex));

Person model = new Person();

model.AutoId = reader.GetInt32(autoIdIndex);

model.UName  = reader.GetString(unameIndex);

model.UAge = reader.IsDBNull(uageIndex) ? null : (int?)reader.GetInt32(uageIndex);

model.UHeight = reader.IsDBNull(uheightIndex) ? null : (int?)reader.GetInt32(uheightIndex);

list.Add (model);

#endregion

}

}

}

}

}

dataGridView1.DataSource = list;

#endregion

/// <summary>

/// 创建Person类,autoId, uname, uage, uheight

/// </summary>

public  class Person

{

public int AutoId

{

get;

set;

}

public string UName

{

get;

set;

}

public int? UAge

{

get;

set;

}

public int? UHeight

{

get;

set;

}

}

第18课-数据库开发及ado.net 连接数据库.增.删.改向表中插入数据并且返回自动编号.SQLDataReade读取数据的更多相关文章

  1. 第19课-数据库开发及ado.net ADO.NET--SQLDataReader使用.SqlProFiler演示.ADoNET连接池,参数化查询.SQLHelper .通过App.Config文件获得连接字符串

    第19课-数据库开发及ado.net ADO.NET--SQLDataReader使用.SqlProFiler演示.ADoNET连接池,参数化查询.SQLHelper .通过App.Config文件获 ...

  2. 第17课-数据库开发及ado.net 聚合函数,模糊查询like,通配符.空值处理.order by排序.分组group by-having.类型转换-cast,Convert.union all; Select 列 into 新表;字符串函数;日期函数

    第17课-数据库开发及ado.net 聚合函数,模糊查询like,通配符.空值处理.order by排序.分组group by-having.类型转换-cast,Convert.union all;  ...

  3. 第16课-数据库开发及ado.net-数据库SQl,创建数据库和表,增删改语句,约束,top和Distinct,聚合函数介绍

    第16课-数据库开发及ado.net 数据库SQl,创建数据库和表,增删改语句,约束,top和Distinct,聚合函数介绍 SQL语句入门(脚本.命令) SQL全名是结构化查询语言(Structur ...

  4. 第20课-数据库开发及ado.net 可空值类型,资料管理器,多条件查询,Case

    第20课-数据库开发及ado.net 可空值类型,资料管理器,多条件查询,Case SqlHelper using System; using System.Collections.Generic; ...

  5. 第15课-数据库开发及ado.net-数据库介绍,主键,外键,启动数据库,数据库身份验证方式,建表,分离数据库

    第15课-数据库开发及ado.net 数据库介绍,主键,外键,启动数据库,数据库身份验证方式,建表,分离数据库 1.  学习方法 2.  多涨见识 3.  比自己强的人一起,学习更强:比自己更聪明的人 ...

  6. 数据库开发及ADO.NET

    大部分数据库都需要数据库服务器才能运行. Catalog(分类)又叫做数据库DataBase Table(表)不同类型的东西放到不同的区域中,将这种区域叫做表. 列(Column)字段Field 主键 ...

  7. ADO.NET 增 删 改 查

    ADO.NET:(数据访问技术)就是将C#和MSSQL连接起来的一个纽带 可以通过ADO.NET将内存中的临时数据写入到数据库中 也可以将数据库中的数据提取到内存中供程序调用 ADO.NET所有数据访 ...

  8. C# ADO.NET (sql语句连接方式)(增,删,改)

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  9. EF Core中,通过实体类向SQL Server数据库表中插入数据后,实体对象是如何得到数据库表中的默认值的

    我们使用EF Core的实体类向SQL Server数据库表中插入数据后,如果数据库表中有自增列或默认值列,那么EF Core的实体对象也会返回插入到数据库表中的默认值. 下面我们通过例子来展示,EF ...

随机推荐

  1. .net core 与ELK(5)安装logstash

    1.下载https://www.elastic.co/downloads/logstash到/usr/local/src wget https://download.elastic.co/logsta ...

  2. C# 简单反射实现winform左侧树形导航,右侧切换内容

    先看看效果: 核心代码: using System; using System.Collections.Generic; using System.ComponentModel; using Syst ...

  3. 4.翻译:EF基础系列--EF架构

    原文地址:http://www.entityframeworktutorial.net/EntityFramework-Architecture.aspx 下面的图形,展示了EF的总体架构: 让我们来 ...

  4. Bootstrap框架下实现图片切换

    准备图片,把相关记录添加至数据库表中: 创建一个存储过程,获取所有记录: 在ASP.NET MVC专案中,部署Bootstrap环境...... 然后创建一个model: using System; ...

  5. Spring IOC 容器源码分析系列文章导读

    1. 简介 Spring 是一个轻量级的企业级应用开发框架,于 2004 年由 Rod Johnson 发布了 1.0 版本.经过十几年的迭代,现在的 Spring 框架已经非常成熟了.Spring ...

  6. .NET Core中使用EF Core连接MySQL

    最近一直在捣鼓.NET Core方面的东西,顺便写下点东西记录下 1.打开vs2017,新建一个项目 2.vs会自动生成一个项目,然后打开NuGet搜索MySql.Data.EntityFramewo ...

  7. eclipse maven打war包

    在eclipse中找到pom.xml文件右键 选择debug as 再选择Maven install运行后 按路径找到生成的war包 推荐https://www.cnblogs.com/qlqwjy/ ...

  8. [0day]微软VS全版本DLL却持漏洞(VS2015 VS2013 VS2012 VS2010 VS2008)

    <无敌破坏王>大师兄说的 "我不是针对谁,而是在座的各位,都是垃圾"前几天在国外论坛看到一个VS2010 DLL却持漏洞 测试发现是全版本 实际上2014年在某越南黑客 ...

  9. POJ 2612

    #include<iostream> #include<stdio.h> #include<algorithm> #define MAXN 11 using nam ...

  10. django-suit报错解决-----from suit.apps import DjangoSuitConfig

    (py27) [root@test SimpletourDevops]# python manage.py makemigrationsTraceback (most recent call last ...