数据库方面的操作示例

1  连接SQL Server数据库示例
// 连接字符串string ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];
// 创建SqlConnection对象SqlConnection connection = new SqlConnection(ConnectionString); try{// 打开数据库连接connection.Open();         myLabel.Text = "连接数据库成功";}catch{myLabel.Text = "连接数据库失败";}finally{// 关闭数据库连接connection.Close();         }<appSettings><add key="ConnectionSqlServer" value="Server=(local);User id=sa;Pwd=sa;Database=Northwind"></add><add key="ConnectionSqlServer1" value="Server=(local);User id=sa;Pwd=sa;"></add><add key="ConnectionSqlServer_tempdb" value="Server=(local);User id=sa;Pwd=sa;Database=tempdb"></add><add key="ConnectionDB2" value="DATABASE=SAMPLE;UID=username;PWD=password"></add><add key="ConnectionOracle" value="Data Source=Oracle8i;Integrated Security=yes"></add></appSettings> <system.web>2  // 连接到 ACCESS 的连接字符串string ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" + Server.MapPath("grocertogo.mdb");// 使用OleDb .NET数据提供程序创建连接OleDbConnection oleConnection = new OleDbConnection(ConnStr);try{// 打开数据库连接oleConnection.Open();// 显示连接成功信息myLabel.Text = "Access数据库连接状态:" + oleConnection.State;}catch(Exception ex){// 如果出现异常,显示异常信息myLabel.Text = "Access数据库连接状态:" + ex.ToString();}finally{// 关闭数据库连接oleConnection.Close(); }3 // 连接到 Oracle 数据库示例string ORACLE_ConnStr = "Data Source=Oracle8i;Integrated Security=yes";// 创建 OracleConnection 对象OracleConnection oConnection = new OracleConnection(ORACLE_ConnStr);try{oConnection.Open();myLabel.Text = "连接到 Oracle 数据库";}catch(Exception ex){myLabel.Text = ex.ToString();}finally{oConnection.Close();}  4 SqlCommand 执行SQL命令示例string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];// 创建SqlConnection对象// 创建Command对象SqlConnection thisConnection = new SqlConnection(ConnStr);SqlCommand thisCommand = new SqlCommand();// 关联Connection对象// 赋值SQL语句到CommandText属性// 指定命令类型是Sql语句thisCommand.Connection = thisConnection;thisCommand.CommandText = "SELECT COUNT(*) FROM Employees";thisCommand.CommandType = CommandType.Text;try{// 打开数据库连接thisCommand.Connection.Open();// 获取查询结果myLabel.Text = thisCommand.ExecuteScalar().ToString();}catch(SqlException ex){// 如果出现异常,在Label标签中显示异常信息myLabel.Text = ex.ToString();}finally{// 关闭数据库连接thisCommand.Connection.Close();}5  SqlDataReader 读取数据示例string ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];string Sql = "SELECT LastName, FirstName FROM Employees";SqlConnection thisConnection = new SqlConnection(ConnectionString);SqlCommand thisCommand = new SqlCommand(Sql, thisConnection);thisCommand.CommandType = CommandType.Text;try{// 打开数据库连接thisCommand.Connection.Open();// 执行SQL语句,并返回DataReader对象SqlDataReader dr = thisCommand.ExecuteReader();// 以粗体显示标题myLabel.Text = "<b>LastName FirstName</b><br>";// 循环读取结果集while(dr.Read()){// 读取两个列值并输出到Label中myLabel.Text += dr["LastName"] + " " + dr["FirstName"] + "<br>";}// 关闭DataReaderdr.Close();}catch(SqlException ex){// 异常处理Response.Write(ex.ToString());}finally{// 关闭数据库连接thisCommand.Connection.Close();}6  使用DataAdapter填充数据到DataSetstring ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];string Sql = "SELECT EmployeeID, LastName, FirstName,Title, TitleOfCourtesy, BirthDate FROM Employees";// 创建SqlConnection对象// 创建DataAdapter对象并初始化SqlConnection thisConnection = new SqlConnection(ConnectionString);SqlDataAdapter adapter = new SqlDataAdapter(Sql, thisConnection);// 创建DataSet对象DataSet data = new DataSet();// 填充数据到DataSetadapter.Fill(data);// 数据绑定myDataGrid.DataSource = data;myDataGrid.DataBind();7 使用DataTable存储数据库表内容string ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];string Sql = "SELECT EmployeeID, LastName, FirstName, BirthDate FROM Employees";// 创建SqlConnection、SqlDataAdapter对象SqlConnection thisConnection = new SqlConnection(ConnectionString);SqlDataAdapter adapter = new SqlDataAdapter(Sql, thisConnection);
// 创建DataTable对象DataTable table = new DataTable();// 填充数据到DataTableadapter.Fill(table);// 将DataTable绑定到DataGrid控件myDataGrid.DataSource = table;myDataGrid.DataBind();8 将数据库数据填充到 XML 文件
// 连接字符串及 SQL 语句string ConnString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];string Sql = "SELECT CustomerID,CompanyName,Country FROM Customers";// 连接 SqlConnection 及 SqlDataAdapter 对象SqlConnection thisConnection = new SqlConnection(ConnString);SqlDataAdapter adapter = new SqlDataAdapter(Sql, thisConnection);// 创建 DataSet 对象DataSet data = new DataSet();// 填充 DataSetadapter.Fill(data, "Customers");// 将 DataSet 数据其及架构填充到 Xml 文件data.WriteXml(Server.MapPath(".") + "\\myXml.xml", XmlWriteMode.WriteSchema);// 提示填充是否成功Label1.Text = "填充到XML文件成功";9 ASP.NET 使用存储过程// 连接字符串string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];// 创建Connection对象SqlConnection myConn = new SqlConnection(ConnStr);// 创建Command对象并和Connection对象关联SqlCommand myCommand = new SqlCommand();myCommand.Connection = myConn;// 指定要执行的存储过程名称myCommand.CommandText = "CustomersProc";// 使用要执行的是存储过程myCommand.CommandType = CommandType.StoredProcedure;// 创建DataAdapter对象填充数据DataSet myDS = new DataSet();SqlDataAdapter adapter = new SqlDataAdapter(myCommand);adapter.Fill(myDS, "Customers");// 将返回的数据和DataGrid绑定显示myDataGrid.DataSource = myDS.Tables["Customers"];myDataGrid.DataBind();10 使用带输入参数的存储过程
string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];// 创建数据库操作对象SqlDataAdapter myAdapter = new SqlDataAdapter();SqlCommand myCommand = new SqlCommand();myCommand.Connection = new SqlConnection(ConnStr);DataTable dt = new DataTable();// 指定要调用的存储过程名称 "Customer_Select"// 指定SqlCommand对象的命令类型为 "StoredProcedure"枚举值myCommand.CommandText = "Customer_Select";myCommand.CommandType = CommandType.StoredProcedure;// 创建SqlParameter对象,指定参数名称、数据类型、长度及参数值SqlParameter para = new SqlParameter("@country", SqlDbType.NVarChar, 15);para.Value = DropDownList1.SelectedValue;myCommand.Parameters.Add(para);// 关联SqlDataAdapter与SqlCommand对象myAdapter.SelectCommand = myCommand;myAdapter.Fill(dt);// 绑定DataGridDataGrid1.DataSource = dt;DataGrid1.DataBind();11 使用带输入、输出参数的存储过程示
string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];// 创建 Connection 和 Command 对象SqlConnection myConn = new SqlConnection(ConnStr);SqlCommand myCommand = new SqlCommand("EmployeesProc", myConn);// 指定要执行的命令为存储过程myCommand.CommandType = CommandType.StoredProcedure;// 增加输入参数并赋值myCommand.Parameters.Add("@TitleOfCourtesy", SqlDbType.NVarChar, 20);myCommand.Parameters["@TitleOfCourtesy"].Value = myDropDownList.SelectedItem.Text;myCommand.Parameters["@TitleOfCourtesy"].Direction = ParameterDirection.Input;// 增加输出参数myCommand.Parameters.Add("@empCount", SqlDbType.Int);myCommand.Parameters["@empCount"].Direction = ParameterDirection.Output;// 创建 DataAdapter 对象填充数据DataSet myDS = new DataSet();SqlDataAdapter adapter = new SqlDataAdapter(myCommand);adapter.Fill(myDS, "Customers");// 使用 Label 控件显示输出参数的输出值rtnLabel.Text = myCommand.Parameters["@empCount"].Value.ToString();// 将返回的数据和 DataGrid 绑定显示myDataGrid.DataSource = myDS.Tables["Customers"];myDataGrid.DataBind();12 获得数据库中表的数目和名称 获取服务器端数据库列表
string listQuery = "SELECT name FROM sysobjects WHERE xtype = 'U'";
string sumQuery = "SELECT COUNT(*) FROM sysobjects WHERE xtype = 'U'string db_query = "sp_helpdb";13 保存图片到SQL Server数据库示例// HttpPostedFile对象,用于读取图象文件属性HttpPostedFile UpFile = UP_FILE.PostedFile;// FileLength 变量存储图片的字节大小int FileLength = UpFile.ContentLength;try{if (FileLength == 0){txtMessage.Text = "<b>您未选择上传的文件</b>";}else{// 创建存储图片文件的临时 Byte 数组Byte[] FileByteArray = new Byte[FileLength];// 建立数据流对象Stream StreamObject = UpFile.InputStream;  // 读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度StreamObject.Read(FileByteArray,0,FileLength);  // 数据库操作string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];string query = "INSERT INTO ImageTable (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@ImageData, @ImageContentType, @ImageDescription, @ImageSize)";SqlCommand myCommand = new SqlCommand(query, new SqlConnection(ConnStr));// 添加各项参数并赋值myCommand.Parameters.Add("@ImageData", SqlDbType.Image);myCommand.Parameters.Add("@ImageContentType", SqlDbType.VarChar, 50);myCommand.Parameters.Add("@ImageDescription", SqlDbType.VarChar, 200);myCommand.Parameters.Add("@ImageSize", SqlDbType.BigInt);myCommand.Parameters["@ImageData"].Value = FileByteArray;myCommand.Parameters["@ImageContentType"].Value = UpFile.ContentType;myCommand.Parameters["@ImageDescription"].Value = txtDescription.Text;myCommand.Parameters["@ImageSize"].Value = FileLength;// 执行数据库操作myCommand.Connection.Open();myCommand.ExecuteNonQuery();myCommand.Connection.Close();// 提示上传成功txtMessage.Text = "<b>上传文件成功</b>";}} catch (Exception ex) {// 使用 Label 标签显示异常txtMessage.Text = ex.Message.ToString();}14 获得插入记录标识号的示例
// 数据库连接字符串string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];// 创建插入SQL语句及调用@@identity函数返回标识值string insert_query = "insert into Categories (CategoryName,Description) values ('IT', 'Internet');"+ "SELECT @@identity AS 'identity';";// 执行数据库操作SqlCommand myCommand = new SqlCommand(insert_query, new SqlConnection(ConnStr));myCommand.Connection.Open();myLabel.Text = myCommand.ExecuteScalar().ToString();myCommand.Connection.Close();
15 如何读取Excel表格中的数据// 获取Excep文件的完整路径string source = File1.Value;string ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + source + ";Extended Properties=Excel 8.0";string query = "SELECT * FROM [Sheet1$]";OleDbCommand oleCommand = new OleDbCommand(query, new OleDbConnection(ConnStr));OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);DataSet myDataSet = new DataSet();// 将 Excel 的[Sheet1]表内容填充到 DataSet 对象oleAdapter.Fill(myDataSet, "[Sheet1$]");// 数据绑定DataGrid1.DataSource = myDataSet;DataGrid1.DataMember = "[Sheet1$]";DataGrid1.DataBind();

转载于:https://www.cnblogs.com/hulang/archive/2010/12/27/1917825.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/435291.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

神经网络与深度学习——TensorFlow2.0实战(笔记)(二)(开发环境介绍)

开发环境介绍 Python3 1.结构清晰&#xff0c;简单易学 2.丰富的标准库 3.强大的的第三方生态系统 4.开源、开放体系 5.高可扩展性&#xff1a;胶水语言 6.高可扩展性&#xff1a;胶水语言 7.解释型语言&#xff0c;实现复杂算法时效率较低 &#xff08;解释型语言是相…

用python做一个简单的投票程序_以一个投票程序的实例来讲解Python的Django框架使...

&#xff08;一&#xff09;关于Django Django是一个基于MVC构造的框架。但是在Django中&#xff0c;控制器接受用户输入的部分由框架自行处理&#xff0c;所以 Django 里更关注的是模型&#xff08;Model&#xff09;、模板(Template)和视图&#xff08;Views&#xff09;&…

做点什么吧

写了6年代码了&#xff0c;回头发现&#xff0c;虽然写了那么多&#xff0c;真正在使用的少的可怜&#xff0c;真正意义上创造性的劳动也少的可怜。大部分时间都在重复着CtrlC和CtrlV&#xff0c;感觉和产线上的工人差不了多少&#xff1f; 总得做点什么吧? 留下点什么&#x…

BSS段、数据段、代码段、堆与栈

BSS段&#xff1a;BSS段&#xff08;bss segment&#xff09;通常是指用来存放程序中未初始化的全局变量的一块内存区域。BSS是英文Block Started by Symbol的简称。BSS段属于静态内存分配。 数据段&#xff1a;数据段&#xff08;data segment&#xff09;通常是指用来存放程序…

python安装模块方法_Python安装模块的几种方法

一、方法1&#xff1a; 单文件模块 直接把文件拷贝到 $python_dir/Lib 二、方法2&#xff1a; 多文件模块&#xff0c;带setup.py 下载模块包&#xff0c;进行解压&#xff0c;进入模块文件夹&#xff0c;执行&#xff1a; python setup.py install 三、 方法3&#xff1a;easy…

使用参数来防止SQL注入

SQL注入的威力是不可忽视的&#xff0c;下面我们主要介绍防范方法——使用参数化SQL。对于不同的数据供应器都有对就的 Parameter 来表示SQL语句或者存储过程中的各种参数。参数和数据库字段的真实类型——对应&#xff0c;所有参数的值会仅仅被认为一个参数。因此&#xff0c;…

高通qca9565网卡驱动_修改注册表让Surface Go的无线网卡支持频段选择

我的Surface Go是第一代无LTE版本&#xff0c;无线网卡型号是Qualcomm Atheros QCA61x4A&#xff0c;因为一些原因急需优先选择5GHz频段wifi的功能&#xff0c;因此写下本文。本文的解决方案仅能保证对Qualcomm Atheros QCA61x4A这一型号的网卡有效&#xff0c;对于其他同品牌不…

异或运算^和他的一个常用作用

发现一个新知识&#xff0c;介绍给大家&#xff1a; 二进制异或运算&#xff1a;两者相等为0,不等为1. 这样我们发现交换两个整数的值时可以不用第三个参数。 如a11,b9.以下是二进制 aa^b1011^10010010; bb^a1001^00101011; aa^b0010^10111001; 这样一来a9,b11了。 举一个运…

微服务 前台调用后台的慢的原因_20年IT农民工分享SpringCloud微服务架构实战文档...

前言越来越多的企业使用 SpringCloud 实现微服务架构设计。我们可以看到这样一种现象&#xff1a;不管是全新开发&#xff0c;还是系统重构&#xff0c;大家似乎都在争先恐后地使用微服务。对于一个Java开发人员来说&#xff0c;学习微服务相关知识大有裨益。本文将从架构设计、…

流量专家为114搜索提供权威流量访问统计

一&#xff1a;系统介绍互联网流量实时统计产品是一套网站流量统计分析系统。致力于为所有网站、第三方统计等用户提供网站流量监控、统计、分析等专业服务。 通过互联网流量实时统计产品 &#xff0c;站长可以随时知道自己网站的被访问情况&#xff0c;每天多少人看了哪些网页…

神经网络与深度学习——TensorFlow2.0实战(笔记)(二)(Anaconda软件介绍)

Anaconda软件介绍 Anaconda下载与安装&#xff08;安装之后会有详细步骤&#xff09; 下载地址&#xff1a; Anaconda官网 https://www.anaconda.com/distribution/ 清华大学软件镜像站 https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/ 软件界面及界面功能介绍 界…

wince 自带的web server

同arm linux相比,wince的网络功能用的相对较少.实际上,wince的网络功能并不逊色,比如"remote display control"就能通过网络远程控制终端. wince自带的web server也是功能强大,绝非arm linux上轻量级的boa之类可比(当然arm linux上有很多其他选择).PB工程加上web se…

Wince6.0p上用ASP技术实现Webserver

一 环境的搭建 1. 内核定制时选上vbscript、javascript&#xff0c;wince6.0自到的web服务器就可以解析vbscript、javascript脚本语言。 2. 数据库的安装 项目中使用的是SQLce3.5数据库&#xff0c;它的安装文件随vs2008一起发布&#xff0c;安装文件有三个&#xff1a;sqlce.w…

opengles 3.0游戏开发_开发者们,快来测试Android Q啦!

近日&#xff0c;谷歌正式推出Android Q Beta 1版本及预览版SDK&#xff0c;TestBird已部署到测试机型&#xff0c;开发者们可到TestBird测试平台测试。此次Android Q 做了不少改进&#xff0c;不少尝鲜的用户反映Android Q对全面屏的手势操作更加友好&#xff0c;整体使用体验…

神经网络与深度学习——TensorFlow2.0实战(笔记)(二)(Anaconda软件使用)

Python的运行模式 交互模式 打开命令行窗口 键入 python&#xff0c;激活python交互模式&#xff0c;出现Python提示符 >>> 在提示符 >>> 处, 写入Python语句 回车&#xff0c;得到Python语句的执行结果 退出Python交互模式 在Python命令提示符后&#…

Ubuntu10.04No init found. Try passing init= bootarg解决方案

在正常状态下误敲 fsck 命令后&#xff0c;果断悲剧。屏幕错误提示错误显示类似于&#xff1a;mount: mounting /dev/disk/by-uuid/***************************** on /rootfailed: Invalid argumentmount: mounting /sys on /root/sys failed: No such file or directorymount…

greenfoot推箱子游戏_推箱子小游戏V2.0更新

小游戏实践推箱子V2.0大家好&#xff0c;我是努力学习争取成为优秀的Game Producer的路人猿&#xff0c;我们上期一起学习制作推箱子的简易V1.0版本&#xff0c;学习了如何响应用户的输入以及面对箱子的各种情况&#xff0c;今天我们把这个程序完善&#xff0c;制作V2.0~ 接着上…

ASP+COM技术在嵌入式Webserver中的应用

1 .COM组件介绍 COM(Component Object Model)&#xff0c;即组件对象模型&#xff0c;它是微软公司开发的一种新的软 件开发技术&#xff0c;Microsoft 的许多技术&#xff0c;如 ActiveX、DirectX、以及 OLE 等都是基于 COM 而建立起来的。COM 标准包括规范和实现两大部分&…

神经网络与深度学习——TensorFlow2.0实战(笔记)(二)(包管理和环境管理)

包管理和环境管理(以下操作也可在anaconda界面&#xff0c;进行可视化操作) 包管理&#xff1a;包的安装、卸载、更新和查找等等 conda命令 conda install <包名称列表> 同时安装多个包 conda install numpy scipy 指定安装的版本(&#xff0c;均可) conda instal…

双向(端)链表、栈、队列

双端链表 双端栈 双端队列 从实用角度,感受不出双端队列的好处,但其可以充当栈和队列的角色. 参考资料:http://baike.baidu.com/view/1627726.htm Test static void Main() {var deque new Deque<int>();Console.WriteLine("Stack:");//stackdeque.AddFirst(1…