SQL Programming using .NET

SQL Programming using .NETSubmitted ByUser LevelDate of SubmissionTimothy VanoverIntermediate02/01/2001Download Project: StoredProcs.zip   192 KB
The StoredProc.exe program can be used to show several different data objects, some draw backs of each and some interesting things, which are not currently working in the beta 1 release quite the way that may be expected. This document will give a high level overview of the objects used.  
To run the program you must have access to a SQL Server. I am using SQL Server 2000, but feel that this can be used just as easily on 6.5 or 7.0.  
In the Framework all data access components are derived from the System.Data object. These include System.Data.ADO and System.Data.SQL. There are several similarities in these as well as differences that need explained.  
System.Data.ADO can be used to connect and manipulate data from multiple data sources, including Access, Oracle, SQL Sever, etc. This library has a connection object that can establish connections to a data source through an OLE DB provider. A connection string might appear as follows:
揚rovider=sqloledb;Initial Catalog=pubs;Data Source=Dev;Uid=sa;Pwd=pass"
As you can see the Provider is the OLE DB provider for connecting to a SQL Sever. The database selected is pubs. The SQL Sever name in this instance is Developer. The Uid is the Login name, and the Pwd is the password for the login.  
This allows generic loosely coupled objects to be reused in making connections and manipulating data to multiple diverse data sources.
System.Data.SQL can only be used to connect and manipulate SQL Server databases. The Provider in the connection string must be omitted as this is encapsulated inside the SQLConnection object. A connection string using this object would appear as follows:  揑nitial Catalog=pubs;Data Source=Dev;Uid=sa;Pwd=pass?nbsp;
The SQL library has been optimized for connections with SQL Server to help with scalability. This is a key issue in many enterprise developments where connections to a database server are an expensive resource. For example to maintain an n-tier projects connections we would not want thousands of connections to the SQL Server all at once. This would take resources and eventually crash the server. The ideal situation is to have a pool of connections that can be reused by multiple clients to connect, make data manipulation, and then exit the connection. At the very least we want to maintain statelessness to our client application so that the resources are not drained. This would also mean that we would not want opened and orphaned connections existing on the server.  
The Profiler is a tool that is installed with SQL Server and allows a wide variety of performance conditions to be examined so that issues can be resolved that may occur.
Information is gathered with a trace set up to monitor the connections to the server created in the Profiler. Below is an example of a stateless connection where data is being retrieved from the database using the System.Data.SQL library. This call comes from the List button on the StoredProcs.exe program.

As you can see by the first and third rows there is a Login, Execution, and a Logout with the trace. Also the duration column shows a value of 130. In the actual program we have made an adhoc query to select the user stored procedures metadata contained in the pubs database sysobjects system table. The actual method call is as follows:
public SQLDataReader SelectProcs(ref SQLConnection cnn)
{
       SQLDataReader dr = null;
       string query = "SELECT Name FROM sysobjects WHERE xtype = 'P' And Category = 0";
       SQLCommand cmd = new SQLCommand(query,cnn);
  
       try
       {
              cmd.CommandType = CommandType.Text;
  
              cmd.Execute(out dr);
       }
       catch(Exception e)
       {
              ErrorLog errLog = new ErrorLog();
                           
              errLog.LogError(e.Message, "Method: SelectProcs");     
       }
                     
       return(dr);
}
The actual connection object is being maintained by the calling method and the data is being returned to the caller. This data is then added to the list box by walking through and reading the data into the list box. An alternative to this could also be binding the results of this query to the list box. The actual screen will now display the stored procedures defined as a type of user as follows.
  
To view the parameters of one of the stored procedures select one from the list box and click the View button. For this example I抣l use the usp_AuthorCol stored procedure. You will notice that the top data grid is now populated with metadata about the stored procedure.

The index column is the ADOCommand.Parameters index value for the parameter listed. The name is the actual name of the parameter. The Type is the actual data type mapped to the Framework data types. The length is a length of the data type. If this had been a string, or for example in SQL a varchar or char, this value would determine the length of the parameter value. The value column is the actual value.
You can select to execute the stored procedure and the bottom grid will be populated with a dataset of the return value. If you have selected an insert, update, or delete stored procedure and have entered a value for the where clause then you can enter a value in the value field and the execute button for executing the stored procedure. You can select the option button to indicate a return value from a select statement or other, which is for insert, update, or delete statements.  

The actual code is simplistic in that it does a parameters-refresh to get the parameters of the stored procedure, and loads them into a data grid so that you can edit the values to send for testing a stored procedure.
Several other points should be made.
1.      The SQLCommand object has a Parameters object, which will not do a Parameters ResetParameters, even though the method is there. I assume that this may be fixed in a future version, as this is a popular method for development and the System.Data.SQL object is tuned for SQL Server.
2.      Connections need to be closed with something like the following.  
if(cnn.State == DBObjectState.Open)
{  
            cnn.Close();
            cnn.Dispose();
   }
3.      Run the Authors.sql sql script to install the usp_Author queries in the pubs database and step through the code. It would also be wise to learn to use the profiler to monitor the connections, and other items that will affect both your queries and your application.
4.      From the testing I have seen there are several items that should be improved when Beta2 is released in the ADOConenction as well. This object or the sqloledb provider has a tendency to keep the connection open until the program is closed even with the close code above.  
Another tool at your disposal, if you are running NT, or Windows 2000 is the event log. This can help you debug your application and find areas where a problem has occurred during the program operation. On the catch methods there is a class, which I have used to encapsulate the writing of data to the event log. You can actually create your own logs for an application or use the one that is present. The EventLog object should be played with as we are now given immense power easily, which required some API calls to do some of what is now as easy as the following code. There are some good examples in the HowTo of the SDK for doing much more than I needed for this project.
internal class ErrorLog
{
/// <summary>
///           This method writes to the application log
/// </summary>
/// <param name="errMessage"> </param>
/// <param name="errSource"> </param>
public void LogError(string errMessage, string errSource)
       {
          EventLog errLog = new System.Diagnostics.EventLog("Application",".",errSource);
  
          errLog.WriteEntry(errMessage, EventLogEntryType.Error);
       }
              
}  
Hope this helps you get some understanding on SQL with .Net. Until the next project is ready,
Timothy A. Vanover MCP, MCT, MCSD, MCDBA
  

时间: 2024-08-31 09:25:41

SQL Programming using .NET的相关文章

《Oracle PL/SQL程序设计(第5版)》一一1.5 PL/SQL开发人员的资源

1.5 PL/SQL开发人员的资源 Oracle PL/SQL程序设计(第5版) O'Reilly在1995年出版了本书的第一版.当时,Oracle PL/SQL编程这本书确实造成一个小轰动.它是第一本关于PL/SQL的独立著作(也就是,不是来自于Oracle公司的).从那时开始,PL/SQL程序员的资源─图书.开发环境.工具以及网站─开始蓬勃发展.(当然,迄今为止这本书仍然是这些资源中最重要和最有价值的!) 下面这一节简要地介绍了这许多资源.要充分利用这些资源,许多资源都可以免费获得或者非常低

《SQL权威指南》作者教你数据库设计1:数据元、域、约束和默认值

写在前面   对于设计和创建数据库完全是个新手?没关系,Joe Celko, 世界上读者数量最多的SQL作者之一,会告诉你这些基础.和往常一样,即使是最专业的数据库老手,也会给他们带来惊喜.Joe是DMBS杂志是多年来最受读者喜爱的作者.他在美国.英国,北欧,南美及非洲传授SQL知识.他在ANSI / ISO SQL标准委员会工作了10年,为SQL-89和SQL-92标准做出了杰出贡献.   一.数据元   在你开始考虑你的数据库架构或表前,你需要细想下你的数据:数据是什么类型,你使用值的范围.

oracle核心和pl/sql编程的参考资料

参考图书  经典的图书  PL/SQL 语言 Oracle PL/SQL Programming Steven Feuerstein with Bill Pribyl http://product.china-pub.com/56915 Oracle PL/SQL程序设计(第5版)(上下册)    体系结构  Expert Oracle Database Architecture Oracle 9i&10g编程艺术 深入数据库体系结构 http://blog.csdn.net/knowhow/M

ASP.NET2.0中的AccessDataSource控件

access|asp.net|控件 ASP.NET 2.0包含了AccessDataSource控件,用来从Access数据库中将数据提取至ASP.NET 2.0(.aspx)页面.这个控件拥有的属性很简单.AccessDataSource的最重要的属性是DataFile属性,用来指向硬盘上MDB文件的路径.AccessDataSource拥有的其他属性还有SelectCommand,用来设定一个显示需要返回的结果集(表和列)的语句.SelectCommand必须使用SQL语法来定义. 在VWD

[Qt教程] 第21篇 数据库(一)Qt数据库应用简介

[Qt教程] 第21篇 数据库(一)Qt数据库应用简介 楼主  发表于 2013-5-13 20:56:39 | 查看: 1403| 回复: 13 Qt数据库应用简介 版权声明 该文章原创于作者yafeilinux,转载请注明出处! 导语 下面十节讲解数据库和XML的相关内容.在学习数据库相关内容前,建议大家掌握一些基本的SQL知识,应该可以看懂基本的SELECT.INSERT.UPDATE和DELETE等语句,因为在这几篇教程中使用的都是非常简单的操作,所以即便没有数据库的专业知识也可以看懂!

oracle数据库的预定义的对象类型

Oracle9i release1 提供了很多有用的,预定义的类型. 类型 描述 xmltype 存储和操作xml数据 多种uri类型 使用这些存储和处理uri(全球统一资源定位), 如根据html 地址获得web 页面 多种any类型 用来定义xml变量并且处理各种类型 都是sys 用户创建的,创建这些类型的脚本:$ORACLE_HOME/rdbms/admin 13.5.1 xmltype Oracle 9i release1 引入了对象类型xmltype.在oracle 9i releas

一种绝对提高开发水平的方法

一.概要 英语对提升软件开发水平非常重要. 如果你英文水平不高,这并不影响你成为一个普通程序员,程序更多是靠逻辑思维. 如果做了多年开发的你发现自己的水平一直上不去,你可能要提高自己的英文水平了,英语就是你技术的瓶颈,对有些人可能是硬伤. 我周围的高水平的开发者英文都不差,官方API,专业英文资料.书籍没问题,代码质量也明显也高许多(比如说命名). 英语是世界上使用最广泛的语言之一,是欧盟.许多国际组织与英联邦国家的官方语言之一.如今英语也是与电脑联系最密切的语言,大多数编程语言都与英语有关系.

对开发者有用的英文网站合集

​​问答社区 Stack Overflow : subscribe to their weekly newsletter and any other topic which you find interesting Quora : A place to share knowledge and better understand the world Learn Anything : Community curated knowledge graph of best paths for learni

[收藏]五种提高 SQL 性能的方法

性能 五种提高 SQL 性能的方法发布日期: 4/1/2004 | 更新日期: 4/1/2004Johnny Papa Data Points Archive 有时, 为了让应用程序运行得更快,所做的全部工作就是在这里或那里做一些很小调整.啊,但关键在于确定如何进行调整!迟早您会遇到这种情况:应用程序中的 SQL 查询不能按照您想要的方式进行响应.它要么不返回数据,要么耗费的时间长得出奇.如果它降低了报告或您的企业应用程序的速度,用户必须等待的时间过长,他们就会很不满意.就像您的父母不想听您解释