《《讲数据库编程》PPT课件.ppt》由会员分享,可在线阅读,更多相关《《讲数据库编程》PPT课件.ppt(34页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、p数据库基础知识p数据库访问技术pADO.NET数据库访问上页上页 下页下页节节末页末页结束结束8.1 8.1 数据库基础知识数据库基础知识基本概念基本概念:数据库数据库 关系模型关系模型 表表 主关键字主关键字MS SQL Server+MS Access+MySql+OracleSQL语句语句:增删改查增删改查SELECT*FROM Contact WHERE(Sex=True)ORDER BY Name ASCINSERT INTO Contact(Name,Sex)Values(Mary,false);UPDATE Contact SET BirthDate=1980/2/2 WHER
2、E Name=MaryDELETE FROM Contact Where Name=Mary;上页上页 下页下页节节末页末页结束结束存储过程存储过程CREATE PROCEDURE UpDateContactByName(Name)ASUPDATE Contact SET Contact.BirthDate=1982/5/6WHERE(Contact.Name)=Name)Go上页上页 下页下页节节末页末页结束结束8.2 8.2 数据库访问技术数据库访问技术RDBMSDirectoryServiceRDBMSEmailODBCOLE DBADOVC+VBDelphilADO.NET作用与作用与
3、ADO相同相同,但与但与.NET FrameWork无缝无缝集成集成,能访问能访问XML,提供断开式的数据访问模型提供断开式的数据访问模型上页上页 下页下页节节末页末页结束结束8.3 ADO.NET8.3 ADO.NET数据库访问数据库访问ADO.NET组成组成:分分.NET数据提供程序和数据提供程序和DataSet两部分两部分,前者用前者用以实现各类数据操作,后者是以实现各类数据操作,后者是ADO.NET断开式数据访问模型断开式数据访问模型的核心的核心,依靠依靠DataAdapter类与数据库通信类与数据库通信.NET Framework数据提供程序的具体实现数据提供程序的具体实现有两个有两
4、个,分别是分别是SQL Server.NET数据提供程序和数据提供程序和OLE DB.NET数据提供程序数据提供程序,前者前者可高效访问可高效访问SQL Server7.0以上版本的数据库以上版本的数据库,后者更通用后者更通用DataBaseXML.NET Data ProviderConnectionCommandDataReaderDataAdapterDataSetDataTableDataColumnDataRowDataRelationConstraint上页上页 下页下页节节末页末页结束结束使用两种使用两种.NET Data Provider.NET Data Provider访问
5、数据库访问数据库SQL Server.NET Data Provider(访问访问SQL Server 7.0数据库数据库)OLE DB.net Data Provider(如访问如访问MS Access数据库数据库)命名空间命名空间using System.Data.SqlClient;using System.Data.OleDb;实例化连接实例化连接SqlConnection conn=new SqlConnection();OleDbConnection conn=new OleDbConnection();连接字符串连接字符串与连接的创与连接的创建与打开建与打开(串有多种(串有多种形
6、式形式,可借可借助助.udl生成)生成)string connStr=“Data Source=(local);Initial Catalog=students;user Id=sa;password=123”;string connStr=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=;connStr+=“Datastudents.mdb;conn.ConnectionString=connStr;conn.open();实例化命令实例化命令执行命令执行命令返回数据流返回数据流SqlCommand cmd=conn.CreateCommand();
7、OleDbCommand cmd=conn.CreateCommand();cmd.CommandType=CommandType.Text;/StoreProcedurecmd.CommandText=Select ID,sName from student;SqlDataReader rd=cmd.ExecuteReader();OleDbDataReader rd=cmd.ExecuteReader();访问数据访问数据while(rd.Read()Cosnsole.Write(reader.GetString(0);关闭关闭reader.close();conn.close();上页上
8、页 下页下页节节末页末页结束结束ADO.NETADO.NET访问访问ACCESSACCESS举例举例控制台输出数据控制台输出数据using System;using System.Data.OleDb;/人工引入人工引入using System.Data;/人工引入人工引入namespace class Program static void Main(string args)OleDbConnection conn=new OleDbConnection();string connStr=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:教学教学d
9、otnetContactDb.mdb;Persist Security Info=False;conn.ConnectionString=connStr;conn.Open();if(conn.State=ConnectionState.Open)Console.WriteLine(ok);OleDbCommand cmd=conn.CreateCommand();cmd.CommandType=CommandType.Text;cmd.CommandText=select*from contact order by Name ASC;OleDbDataReader rd=cmd.Execut
10、eReader();while(rd.Read()Console.WriteLine(0,1,2,3,rd.GetInt32(0),rd.GetString(1),rd.GetBoolean(2)?男男:女女,rd.GetDateTime(3).ToShortDateString();rd.Close();conn.Close();上页上页 下页下页节节末页末页结束结束ADO.NETADO.NET访问访问MS SQL ServerMS SQL Server数据库举例:数据库举例:SqlConnection conn;SqlDataReader reader;try conn=new SqlCo
11、nnection();string connStr=“Data Source=(local);Initial Catalog=students;user Id=bb;password=bb”;/也可用也可用sa conn.ConnectionString=connStr;conn.Open();if(conn.State=ConnectionState.Open)MessageBox.Show(接接通通);SqlCommand cmd=conn.CreateCommand();cmd.CommandType=CommandType.Text;cmd.CommandText=Select ID,
12、sName from student;reader=cmd.ExecuteReader();string output;while(reader.Read()output=string.Format(学生学生0t学号是学号是1n,reader.GetString(1),reader.GetInt32(0);lblOutput.Text=lblOutput.Text+output;catch(Exception ex)MessageBox.Show(“操作操作失败失败+ex.Message);finally reader.Close();conn.Close();上页上页 下页下页节节末页末页结
13、束结束再例:注意命令的创建与异常的处理再例:注意命令的创建与异常的处理using System;using System.Data.OleDb;using System.Data;namespace class Program static void Main(string args)string connStr=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:教学教学dotnetContactDb.mdb;Persist Security Info=False;using(OleDbConnection conn=new OleDbConnect
14、ion()conn.ConnectionString=connStr;conn.Open();if(conn.State=ConnectionState.Open)Console.WriteLine(ok);OleDbCommand cmd=new OleDbCommand();cmd.Connection=conn;cmd.CommandType=CommandType.Text;cmd.CommandText=select*from contact order by Name ASC;OleDbDataReader rd=cmd.ExecuteReader();while(rd.Read(
15、)Console.WriteLine(0,1,2,3,rd.GetInt32(0),rd.GetString(1),rd.GetBoolean(2)?男男:女女,rd.GetDateTime(3).ToShortDateString();rd.Close();上页上页 下页下页节节末页末页结束结束CommandCommand详解详解SQL ServerAccess通过已存在通过已存在数据库连接数据库连接实例化命令实例化命令SqlCommand cmd=conn.CreateCommand();OleDbCommand cmd=conn.CreateCommand();cmd.CommandTe
16、xt=Select ID,sName from student;用构造函数用构造函数实例化命令实例化命令对象并赋值对象并赋值SqlCommand cmd=new SqlCommand();cmd.Connection=conn;cmd.CommandText=commandString;cmd.CommandType=CommandType.Text/StoredProcedureSqlCommand cmd=new SqlCommand(CommandText);SqlCommand cmd=new SqlCommand(CommandText,ConnectionObject);命令对象的
17、命令对象的成员方法成员方法ExecuteNonQuery:插入、更新、删除,不返回结果:插入、更新、删除,不返回结果ExecuteScalar:执行返回单个值的命令执行返回单个值的命令ExecuteReader:返回一个:返回一个DataReader对象对象ExecuteXmlReader:返回返回XmlReader对象对象,SqlCommand特有特有上页上页 下页下页节节末页末页结束结束向数据库插入一条记录向数据库插入一条记录using System;using System.Data.OleDb;using System.Data;namespace class Program stat
18、ic void Main(string args)string connStr=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:教学教学dotnetContactDb.mdb;Persist Security Info=False;using(OleDbConnection conn=new OleDbConnection()conn.ConnectionString=connStr;conn.Open();OleDbCommand cmd=new OleDbCommand();cmd.Connection=conn;cmd.CommandType
19、=CommandType.Text;cmd.CommandText=INSERT INTO Contact(Name,Sex,BirthDate)Values(Mary,false,1980/5/5);int count=cmd.ExecuteNonQuery();Console.WriteLine(共共0行被改变行被改变,count);更新:更新:UPDATE Contact SET telephone=123456789 Where(name=Mary);删除删除:cmd.CommandText=DELETE FROM Contact Where Name=Mary;上页上页 下页下页节节
20、末页末页结束结束利用用带参数的利用用带参数的SQLSQL语句语句 :(处理复杂表和赋变量值更清晰处理复杂表和赋变量值更清晰)static void Main(string args)string connStr=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:教学教学dotnetContactDb.mdb;Persist Security Info=False;using(OleDbConnection conn=new OleDbConnection()conn.ConnectionString=connStr;conn.Open();OleDb
21、Command cmd=new OleDbCommand();cmd.Connection=conn;cmd.CommandType=CommandType.Text;cmd.CommandText=INSERT INTO Contact(Name,Sex,BirthDate)Values(Name,Sex,BirthDate);OleDbParameter parms=new OleDbParameter new OleDbParameter(Name,OleDbType.VarChar,50),new OleDbParameter(Sex,OleDbType.Boolean),new Ol
22、eDbParameter(BirthDate,OleDbType.Date);parms0.Value=Mary;parms1.Value=true;parms2.Value=Convert.ToDateTime(“1977/5/6”);/可隐式转换可隐式转换 cmd.Parameters.AddRange(parms);int count=cmd.ExecuteNonQuery();Console.WriteLine(共共0行被改变行被改变,count);上页上页 下页下页节节末页末页结束结束对比:将文本框中的数据放入对比:将文本框中的数据放入sqlsql语句语句cmd.CommandTex
23、t=INSERT INTO Contact(Name,Sex,BirthDate)Values(+textBox1.Text+,+textBox2.Text+,+textBox3.Text+);用带参数的用带参数的SQL语句更清晰语句更清晰cmd.CommandText=INSERT INTO Contact(Name,Sex,BirthDate)Values(Name,Sex,BirthDate);OleDbParameter parms=new OleDbParameter new OleDbParameter(Name,OleDbType.VarChar,50),new OleDbPar
24、ameter(Sex,OleDbType.Boolean),new OleDbParameter(BirthDate,OleDbType.Date);parms0.Value=textBox1.Text;parms1.Value=Convert.ToBoolean(textBox2.Text);/可隐式转换可隐式转换parms2.Value=Convert.ToDateTime(textBox3.Text);/可隐式转换可隐式转换cmd.Parameters.AddRange(parms);上页上页 下页下页节节末页末页结束结束DataDataReaderReader详解详解SQL Serve
25、rAccess数据阅读器数据阅读器对象的创建对象的创建SqlDataReader reader=cmd.ExecuteReader();OleDbDataReader reader=cmd.ExecuteReader();遍历数据阅遍历数据阅读器中的记读器中的记录录while(rd.read()rd.getInt32(0);(int)reader0;或或(int)reader“ID”;rd.GetInt32(0);rd.GetString(1);rd.GetBoolean(2)?男男:女女,rd.GetDateTime(3).ToShortDateString()(Boolean)rd2)?男
26、:女,(DateTime)rd3).ToShortDateString();rd“Name”;rd“Sex”;/返回Object类型,需同上进行类型转换上页上页 下页下页节节末页末页结束结束关于数据集关于数据集DataSetDataSet和绑定和绑定l前者对于复杂数据库操作不适用,后者前者对于复杂数据库操作不适用,后者简化了操作,但破坏了三层结构,通常简化了操作,但破坏了三层结构,通常不提倡使用,自学不提倡使用,自学上页上页 下页下页节节末页末页结束结束回顾:连接数据库并执行查询命令回顾:连接数据库并执行查询命令using System;using System.Data.OleDb;/自行引
27、入自行引入using System.Data;/自行引入自行引入namespace class Program static void Main(string args)string connStr=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:教学教学dotnetContactDb.mdb;Persist Security Info=False;using(OleDbConnection conn=new OleDbConnection()conn.ConnectionString=connStr;conn.Open();if(conn.Sta
28、te=ConnectionState.Open)Console.WriteLine(ok);OleDbCommand cmd=new OleDbCommand();cmd.Connection=conn;cmd.CommandType=CommandType.Text;cmd.CommandText=select*from contact order by Name ASC;OleDbDataReader rd=cmd.ExecuteReader();while(rd.Read()/实际应先判断是否有行实际应先判断是否有行 Console.WriteLine(0,1,2,3,rd.GetInt
29、32(0),rd.GetString(1),rd.GetBoolean(2)?男男:女女,rd.GetDateTime(3).ToShortDateString();rd.Close();上页上页 下页下页节节末页末页结束结束连接数据库并执行增删改命令连接数据库并执行增删改命令using System;using System.Data.OleDb;using System.Data;namespace class Program static void Main(string args)string connStr=Provider=Microsoft.Jet.OLEDB.4.0;Data
30、Source=D:教学教学dotnetContactDb.mdb;Persist Security Info=False;using(OleDbConnection conn=new OleDbConnection()conn.ConnectionString=connStr;conn.Open();OleDbCommand cmd=new OleDbCommand();cmd.Connection=conn;cmd.CommandType=CommandType.Text;cmd.CommandText=INSERT INTO Contact(Name,Sex,BirthDate)Value
31、s(Mary,false,1980/5/5);int count=cmd.ExecuteNonQuery();Console.WriteLine(共共0行被改变行被改变,count);更新:更新:UPDATE Contact SET telephone=123456789 Where(name=Mary);删除删除:cmd.CommandText=DELETE FROM Contact Where Name=Mary;上页上页 下页下页节节末页末页结束结束带参数的带参数的SQLSQL语句语句 :static void Main(string args)string connStr=Provid
32、er=Microsoft.Jet.OLEDB.4.0;Data Source=D:教学教学dotnetContactDb.mdb;Persist Security Info=False;using(OleDbConnection conn=new OleDbConnection()conn.ConnectionString=connStr;conn.Open();OleDbCommand cmd=new OleDbCommand();cmd.Connection=conn;cmd.CommandType=CommandType.Text;cmd.CommandText=INSERT INTO
33、Contact(Name,Sex,BirthDate)Values(Name,Sex,BirthDate);OleDbParameter parms=new OleDbParameter new OleDbParameter(Name,OleDbType.VarChar,50),new OleDbParameter(Sex,OleDbType.Boolean),new OleDbParameter(BirthDate,OleDbType.Date);parms0.Value=Mary;parms1.Value=true;parms2.Value=Convert.ToDateTime(“1977
34、/5/6”);/可隐式转换可隐式转换 cmd.Parameters.AddRange(parms);int count=cmd.ExecuteNonQuery();Console.WriteLine(共共0行被改变行被改变,count);上页上页 下页下页节节末页末页结束结束对比:将文本框中的数据放入对比:将文本框中的数据放入sqlsql语句语句cmd.CommandText=INSERT INTO Contact(Name,Sex,BirthDate)Values(+textBox1.Text+,+textBox2.Text+,+textBox3.Text+);用带参数的用带参数的SQL语句
35、更清晰语句更清晰cmd.CommandText=INSERT INTO Contact(Name,Sex,BirthDate)Values(Name,Sex,BirthDate);OleDbParameter parms=new OleDbParameter new OleDbParameter(Name,OleDbType.VarChar,50),new OleDbParameter(Sex,OleDbType.Boolean),new OleDbParameter(BirthDate,OleDbType.Date);parms0.Value=textBox1.Text;parms1.Val
36、ue=Convert.ToBoolean(textBox2.Text);/可隐式转换可隐式转换parms2.Value=Convert.ToDateTime(textBox3.Text);/可隐式转换可隐式转换cmd.Parameters.AddRange(parms);上页上页 下页下页节节末页末页结束结束三层结构开发:三层结构开发:l表现层表现层(Client):MainForm窗体窗体,常用常用DataGridView(参参考教材考教材)或或ListView控件控件(参考视频,通过参考视频,通过Columns属性添属性添加字段名加字段名,设置设置FullRowSelect和和 Gridl
37、ines为为Ture,设置,设置View属性为属性为Details)l业务逻辑层业务逻辑层(Business):ContactBiz类类,提供静态方法提供静态方法l数据服务层数据服务层(DataAccess):ContactDaol类类,提供静态方法提供静态方法l实体模型类实体模型类(Model):ContactInfo类类,封装各字段封装各字段,对应一对应一行行上页上页 下页下页节节末页末页结束结束实体类:注意字段、属性修饰符及可空类型实体类:注意字段、属性修饰符及可空类型class ContactInfo private int _id;public int Id/重构重构封装字段封装字段
38、 get return _id;set _id=value;private string _name;public string Name private bool?_sex;/可空类型,因数据库中此字段可空可空类型,因数据库中此字段可空 public bool?Sex /可空类型可空类型 get return _sex;set _sex=value;private DateTime?_birthDate;public DateTime?BirthDate private string _telePhone;/引用类型本身就可为空引用类型本身就可为空 public string TelePho
39、ne get return _telePhone;set _telePhone=value;上页上页 下页下页节节末页末页结束结束数据服务层:数据服务层:class ContactDao private const string CONN_STRING=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:教学教学dotnetContactDb.mdb;Persist Security Info=False;private const string INSERT_STRING=INSERT INTO Contact(Name,Sex,BirthDate,
40、TelePhone)Values(Name,Sex,BirthDate,TelePhone);private const string DELETE_STRING=DELETE FROM Contact WHERE ID=ID;private const string UPDATE_STRING=UPDATE Contact SET Name=Name,Sex=Sex,BirthDate=BirthDate,TelePhone=TelePhone Where ID=ID;private const string SELECT_ALL_STRING=SELECT*FROM Contact;pri
41、vate const string SELECT_BY_NAME_STRING=SELECT*FROM Contact Where Name=Name;public static int InsertInfo(ContactInfo contactInfo)public static int DeleteInfo(int Id)public static int UpdateInfo(ContactInfo contactInfo)public static IList GetAllContact()public static IList GetByName(string name)上页上页
42、下页下页节节末页末页结束结束public static int InsertInfo(ContactInfo contactInfo)using(OleDbConnection conn=new OleDbConnection()conn.ConnectionString=CONN_STRING;conn.Open();OleDbCommand cmd=new OleDbCommand();cmd.Connection=conn;cmd.CommandType=CommandType.Text;cmd.CommandText=INSERT_STRING;OleDbParameter parms
43、=new OleDbParameter new OleDbParameter(Name,OleDbType.VarChar,50),new OleDbParameter(Sex,OleDbType.Boolean),new OleDbParameter(BirthDate,OleDbType.Date),new OleDbParameter(TelePhone,OleDbType.VarChar,50);parms0.Value=contactInfo.Name;parms1.IsNullable=true;if(contactInfo.Sex.HasValue)parms1.Value=co
44、ntactInfo.Sex;else parms1.Value=DBNull.Value;parms2.IsNullable=true;if(contactInfo.BirthDate.HasValue)parms2.Value=contactInfo.BirthDate;else parms2.Value=DBNull.Value;parms3.IsNullable=true;if(String.IsNullOrEmpty(contactInfo.TelePhone)parms3.Value=DBNull.Value;else parms3.Value=contactInfo.TelePho
45、ne;cmd.Parameters.AddRange(parms);return(cmd.ExecuteNonQuery();上页上页 下页下页节节末页末页结束结束 public static int DeleteInfo(int Id)using(OleDbConnection conn=new OleDbConnection()conn.ConnectionString=CONN_STRING;conn.Open();OleDbCommand cmd=new OleDbCommand();cmd.Connection=conn;cmd.CommandType=CommandType.Tex
46、t;cmd.CommandText=DELETE_STRING;OleDbParameter parms=new OleDbParameter new OleDbParameter(ID,OleDbType.Integer);parms0.Value=Id;cmd.Parameters.AddRange(parms);return(cmd.ExecuteNonQuery();上页上页 下页下页节节末页末页结束结束public static IList GetAllContact()List contactList=new List();using(OleDbConnection conn=ne
47、w OleDbConnection()conn.ConnectionString=CONN_STRING;conn.Open();OleDbCommand cmd=new OleDbCommand();cmd.Connection=conn;cmd.CommandType=CommandType.Text;cmd.CommandText=SELECT_ALL_STRING;using(OleDbDataReader rd=cmd.ExecuteReader()if(rd.HasRows)while(rd.Read()ContactInfo contactInfo=featch(rd);cont
48、actList.Add(contactInfo);return contactList;private static ContactInfo featch(OleDbDataReader rd)ContactInfo contactInfo=new ContactInfo();contactInfo.Id=rd.GetInt32(0);contactInfo.Name=rd.GetString(1);if(!rd.IsDBNull(2)contactInfo.Sex=rd.GetBoolean(2);if(!rd.IsDBNull(3)contactInfo.BirthDate=rd.GetD
49、ateTime(3);if(!rd.IsDBNull(4)contactInfo.TelePhone=rd.GetString(4);return contactInfo;上页上页 下页下页节节末页末页结束结束业务逻辑层:业务逻辑层:class ContactBiz public static int InsertInfo(ContactInfo contactInfo)return ContactDao.InsertInfo(contactInfo);/之之前应判断是否前应判断是否重名重名 public static int DelteInfo(int Id)return ContactDa
50、o.DeleteInfo(Id);public static int UpdateInfo(ContactInfo contactInfo)return ContactDao.UpdateInfo(contactInfo);public static IList GetAllContact()return ContactDao.GetAllContact();public static IList GetByName(string name)return(ContactDao.GetByName(name);上页上页 下页下页节节末页末页结束结束表现层:控制台界面,测试使用表现层:控制台界面,