第18课-数据库开发及ado.net 连接数据库.增.删.改向表中插入数据并且返回自动编号.SQLDataReade读取数据
第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读取数据的更多相关文章
- 第19课-数据库开发及ado.net ADO.NET--SQLDataReader使用.SqlProFiler演示.ADoNET连接池,参数化查询.SQLHelper .通过App.Config文件获得连接字符串
第19课-数据库开发及ado.net ADO.NET--SQLDataReader使用.SqlProFiler演示.ADoNET连接池,参数化查询.SQLHelper .通过App.Config文件获 ...
- 第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; ...
- 第16课-数据库开发及ado.net-数据库SQl,创建数据库和表,增删改语句,约束,top和Distinct,聚合函数介绍
第16课-数据库开发及ado.net 数据库SQl,创建数据库和表,增删改语句,约束,top和Distinct,聚合函数介绍 SQL语句入门(脚本.命令) SQL全名是结构化查询语言(Structur ...
- 第20课-数据库开发及ado.net 可空值类型,资料管理器,多条件查询,Case
第20课-数据库开发及ado.net 可空值类型,资料管理器,多条件查询,Case SqlHelper using System; using System.Collections.Generic; ...
- 第15课-数据库开发及ado.net-数据库介绍,主键,外键,启动数据库,数据库身份验证方式,建表,分离数据库
第15课-数据库开发及ado.net 数据库介绍,主键,外键,启动数据库,数据库身份验证方式,建表,分离数据库 1. 学习方法 2. 多涨见识 3. 比自己强的人一起,学习更强:比自己更聪明的人 ...
- 数据库开发及ADO.NET
大部分数据库都需要数据库服务器才能运行. Catalog(分类)又叫做数据库DataBase Table(表)不同类型的东西放到不同的区域中,将这种区域叫做表. 列(Column)字段Field 主键 ...
- ADO.NET 增 删 改 查
ADO.NET:(数据访问技术)就是将C#和MSSQL连接起来的一个纽带 可以通过ADO.NET将内存中的临时数据写入到数据库中 也可以将数据库中的数据提取到内存中供程序调用 ADO.NET所有数据访 ...
- C# ADO.NET (sql语句连接方式)(增,删,改)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
- EF Core中,通过实体类向SQL Server数据库表中插入数据后,实体对象是如何得到数据库表中的默认值的
我们使用EF Core的实体类向SQL Server数据库表中插入数据后,如果数据库表中有自增列或默认值列,那么EF Core的实体对象也会返回插入到数据库表中的默认值. 下面我们通过例子来展示,EF ...
随机推荐
- redis集群(主从配置)
市面上太多kv的缓存,最常用的就属memcache了,但是memcache存在单点问题,不过小日本有复制版本,但是使用的人比较少,redis的出现让kv内存存储的想法成为现实.今天主要内容便是redi ...
- 9.翻译:EF基础系列---使用EF开发的方式有哪些?
原文链接:http://www.entityframeworktutorial.net/choosing-development-approach-with-entity-framework.aspx ...
- AEAI WM v1.6.0 升级说明,开源工作管理系统
1 升级说明 AEAI WM v1.6.0版是AEAI WM v1.5.0版工作管理系统的升级版本,本次升级的系统是基于AEAI DP 3.8.0_20170228进行打包部署的,对产品中的功能及BU ...
- 【js】关于正则表达式
正则表达式描述了字符的模式对象 语法: var patt=new RegExp(pattern,modifiers); 或更简单的方法 var patt=/pattern/modifiers; 模式描 ...
- 【BZOJ3555】 [Ctsc2014]企鹅QQ
BZOJ3555 [Ctsc2014]企鹅QQ Solution 只需要前缀Hash,然后考虑每一段的贡献就好了!!! 代码实现 #include<stdio.h> #include< ...
- spring boot 中使用LUA脚本
编写LUA脚本 该脚本功能:先检查redis中某个key的值是否与期望的值V1一致,如果一致则将其修改为新的值V2并返回true,否则返回false.其实就是CAS. local current = ...
- 用.NET WebService Studio调试Web Service解决SOAPAction的问题
话说是这样的,这两天开发一个短信发送功能,客户给了一个 Web Service 地址(没有文档),让我调用就可以发送了, 我在VS 2013添加了服务引用,一切正常,可是执行代理方法时,怎么都报错 R ...
- 防止活动上线时 微信openid 被伪造的解决办法
背景 前不久上线了一个 campaign 项目,一个 h5,后端为php,用户可以在微信中通过网页授权的方式登录,然后用微信 openid 作为唯一标识符进行签到和抽奖的操作. 结果后期出现了很多脏数 ...
- 【sping揭秘】7、国际化信息支持
Spring提供messagesource接口,来进行国际化事务处理 Applicationcontext会优先找一个名为messageSouce的messageSource接口实现bean,如果找不 ...
- #Python学习#python虚拟环境——virtualenv
前言 在Ubuntu系统中,系统一般会默认安装python2.x和3.x,像我近期买的阿里云ECS默认安装了2.7.2和3.5.2,所有pip安装的第三方包都会被放在默认的site-apckages目 ...