实验四文件和数据库访问技术训练.docx
- 文档编号:3541380
- 上传时间:2022-11-23
- 格式:DOCX
- 页数:16
- 大小:169.48KB
实验四文件和数据库访问技术训练.docx
《实验四文件和数据库访问技术训练.docx》由会员分享,可在线阅读,更多相关《实验四文件和数据库访问技术训练.docx(16页珍藏版)》请在冰豆网上搜索。
实验四文件和数据库访问技术训练
实验四文件和数据库访问技术训练
【1】能力培养要求:
掌握基本文件和数据库的读写方法
【2】实验内容、目的、要求:
了解流的概念,熟悉基本文件的读写方法;了解数据源的概念,掌握数据库的读写方法;能通过存储过程访问数据库。
【3】实验步骤:
本实验中所包含的以下项目均存放在名称为Lab4的解决方案中,该解决方案存放在D盘上。
1、文件读写训练
创建控制台项目ConsoleApplication,在Main中编写程序完成如下功能:
读入一段文本(article.txt),统计文本中出现单词的个数,并以“单词个数:
24”的形式写入到此文本尾部(假设文本中有24个单词)。
标点“,”、“.”和空格作为分隔符,并假设文本中只有这3种符号和单词。
代码的编写可参考P118—P119代码。
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.IO;
namespaceConsoleApplication
{
publicclassTextFromFile
{
staticvoidMain(string[]args)
{
intnum=0;
intword=0;
stringFILE_NAME="..\\..\\article.txt";
if(!
File.Exists(FILE_NAME))
{
Console.WriteLine(FILE_NAME+"不存在");
Console.ReadLine();
return;
}
StreamReadersr=File.OpenText(FILE_NAME);
Stringinput;
while((input=sr.ReadLine())!
=null)
{
for(inti=0;i { if(input[i]==''||input[i]==','||input[i]=='.') word=0; else if(word==0) { word=1; num++; } } } sr.Close(); StreamWritersw=File.AppendText(FILE_NAME); sw.WriteLine("单词个数: "+num); Console.WriteLine("统计完成! 单词个数: "+num); Console.ReadLine(); sw.Close(); } } } 2、序列化训练 使用BinnaryFormatter进行序列化和反序列化。 创建Windows应用程序,名称为WindowsApplication。 设计表单Form1,界面如下图: 通过界面中的控件完成对如下类的序列化: publicclassClassToSerialize { publicintid; publicstringname; [NonSerialized] publicstringSex; } 具体要求: 单击按钮“序列化”时,当文本框输入不全时,显示“信息输入不全”;否则将所填信息序列化到文件“temp.data”中,并提示“序列化成功! ”。 单击按钮“反序列化”时,在表单的标签上显示结果,如下图: 思考: 为什么结果中没有性别信息? 代码的编写可参考P128—P129代码。 usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.IO; usingSystem.Runtime.Serialization; usingSystem.Runtime.Serialization.Formatters.Binary; namespaceWindowsFormsApplication { publicpartialclassForm1: Form { publicForm1() { InitializeComponent(); } [Serializable] publicclassClassToSerialize { publicintid; publicstringname; [NonSerialized] publicstringSex; } privatevoidbutton1_Click(objectsender,EventArgse) { ClassToSerializemyInfo=newClassToSerialize(); if(textBox1.Text==string.Empty||textBox2.Text==string.Empty) { MessageBox.Show("请输入正确的信息! "); } else { myInfo.id=int.Parse(textBox1.Text); myInfo.name=textBox2.Text; if(radioButton2.Checked) myInfo.Sex=radioButton2.Text; else myInfo.Sex=radioButton1.Text; MessageBox.Show("序列化成功! "); } FileStreamfileStream=newFileStream("temp.dat",FileMode.Create); BinaryFormatterb=newBinaryFormatter(); b.Serialize(fileStream,myInfo); fileStream.Close(); } privatevoidbutton2_Click(objectsender,EventArgse) { ClassToSerializemyInfo=newClassToSerialize(); FileStreamfileStream=newFileStream("temp.dat",FileMode.Open,FileAccess.Read,FileShare.Read); BinaryFormatterb=newBinaryFormatter(); myInfo=b.Deserialize(fileStream)asClassToSerialize; fileStream.Close(); label4.Text="反序列化的结果为: "+myInfo.id+""+myInfo.name+""+myInfo.Sex; } } } 3、数据库读取训练 本实验中使用的连接字符串如下: "DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|NORTHWND.MDF; IntegratedSecurity=True;UserInstance=True" 1)使用DataAdapter和DataSet访问数据库 创建Windows应用程序,名称为DataBaseLx。 设计表单Form1,界面如下图: 当点击“取数据”按钮时,效果如下图(读取数据库“NORTHWND.MDF”中的表“Employees”的三列信息): 当点击“生成XML”按钮后,效果如下: “取数据”按钮中的代码参考P144。 usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.Data.SqlClient; namespaceDataBaseLx { publicpartialclassForm1: Form { publicForm1() { InitializeComponent(); } DataSetds=newDataSet(); privatevoidbutton1_Click(objectsender,EventArgse) { SqlConnectionmyConnection=newSqlConnection(@"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|NORTHWND.MDF;IntegratedSecurity=True;UserInstance=True"); SqlDataAdaptercustomersTableAdapter=newSqlDataAdapter("SelectEmployeeID,FirstName,LastNameFROMEmployees",myConnection); customersTableAdapter.Fill(ds,"Employees"); dataGridView1.DataSource=ds.Tables[0]; button2.Enabled=true; button1.Enabled=false; } privatevoidbutton2_Click(objectsender,EventArgse) { ds.Tables[0].WriteXml("Employees.xml",XmlWriteMode.IgnoreSchema); MessageBox.Show("生成Employees.xml文件! "); button2.Enabled=false; } privatevoidForm1_Load(objectsender,EventArgse) { button2.Enabled=false; } } } 2)使用Command和DataReader访问数据库 在项目DataBaseLx中添加表单Form2,运行时显示效果如下图,单击列的头部,观察能否排序。 参考P149代码。 usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.Data.SqlClient; namespaceDataBaseLx { publicpartialclassForm2: Form { publicForm2() { InitializeComponent(); } privatevoidForm2_Load(objectsender,EventArgse) { SqlConnectionmyConnection=newSqlConnection(@"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|NORTHWND.MDF;IntegratedSecurity=True;UserInstance=True"); SqlCommandmyCommand=newSqlCommand("SelectEmployeeID,FirstName,LastNameFROMEmployees",myConnection); myConnection.Open(); SqlDataReadermyReader=myCommand.ExecuteReader(); BindingSourcebs=newBindingSource(); bs.DataSource=myReader; dataGridView1.DataSource=bs; myReader.Close(); myConnection.Close(); } } } 3)存储过程的使用 在项目DataBaseLx中添加表单Form3,要求使用数据库“NORTHWND.MDF”中的存储过程“TenMostExpensiveProducts”查询最贵的10种产品,结果显示在datagridveiw上。 运行效果如下图: 参考P153代码。 usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.Data.SqlClient; namespaceDataBaseLx { publicpartialclassForm3: Form { publicForm3() { InitializeComponent(); } privatevoidForm3_Load(objectsender,EventArgse) { SqlConnectionmyConnection=newSqlConnection(@"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|NORTHWND.MDF;IntegratedSecurity=True;UserInstance=True"); SqlCommandmyCommand=newSqlCommand("SelectTenMostExpensiveProducts,UnitPriceFROMProducts",myConnection); myConnection.Open(); SqlDataAdaptermySqlDataAdapter=newSqlDataAdapter(); mySqlDataAdapter.SelectCommand=newSqlCommand(); mySqlDataAdapter.SelectCommand.Connection=myConnection; mySqlDataAdapter.SelectCommand.CommandText="TenMostExpensiveProducts"; mySqlDataAdapter.SelectCommand.CommandType=CommandType.StoredProcedure; DataSetmyDataSet=newDataSet(); mySqlDataAdapter.Fill(myDataSet,"Products"); dataGridView1.DataSource=myDataSet.Tables["Products"]; } } } 4)使用视图进行排序和筛选 在项目DataBaseLx中添加表单Form4,界面设计如下图: 运行时出现如下画面: 在第一个列表框中显示从Employees表中读取的Title字段,用于筛选的条件;第二个列表框中存放条目“EmployeeID,FirstName,LastName,Title”,用于排序的字段;通过单选按钮进行排序方式的选择。 点击“确定”按钮后,在下方的DataGridView中显示所选的Title的记录,并按所选的字段按指定的方式进行排序。 运行效果如下图: 排序和筛选功能的实现参考P146代码。 usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.Data.SqlClient; namespaceDataBaseLx { publicpartialclassForm4: Form { publicForm4() { InitializeComponent(); } privatevoidForm4_Load(objectsender,EventArgse) { SqlConnectionmyConnection=newSqlConnection(@"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|NORTHWND.MDF;IntegratedSecurity=True;UserInstance=True"); SqlDataAdaptermyAdapter=newSqlDataAdapter("SelectdistincttitlefromEmployees",myConnection); DataSetds=newDataSet(); myAdapter.Fill(ds,"Title"); comboBox1.DataSource=ds.Tables["Title"]; comboBox1.DisplayMember="Title"; } privatevoidbutton1_Click(objectsender,EventArgse) { SqlConnectionmyConnection=newSqlConnection(@"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|NORTHWND.MDF;IntegratedSecurity=True;UserInstance=True"); SqlDataAdaptermyAdapter=newSqlDataAdapter("SelectEmployeeID,FirstName,LastName,TitlefromEmployees",myConnection); DataSetds=newDataSet(); myAdapter.Fill(ds,"Employees"); dataGridView1.DataSource=ds.Tables["Employees"].DefaultView; ds.Tables["Employees"].DefaultView.RowFilter="Title='"+comboBox1.Text+"'"; stringmode="Asc"; if(radioButton2.Checked) mode="Desc"; if(comboBox2.Text! =string.Empty) ds.Tables["Employees"].DefaultView.Sort=comboBox2.Text+mode; } } } 【4】思考题 1、文件流的参数有哪几个? 2、什么是序列化和反序列化? 3、比较使用DataSet和DataReader来访问数据过程。
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 实验四 文件和数据库访问技术训练 实验 文件 数据库 访问 技术 训练
![提示](https://static.bdocx.com/images/bang_tan.gif)