search
HomeDatabaseMysql Tutorial.NET数据库连接中的对象

.NET数据库连接中的对象

Jun 07, 2016 pm 03:56 PM
.netstudyobjectdatabasevideoconnect

在学习VB.NET视频时,其中有几个单元讲到了.NET的数据库设计与连接。对于数据库的连接,其实我们并不陌生,原来在做红皮书和机房收费系统的时候,我们都有接触过,可是,在我的印象中,这些关于数据库连接的知识很是模糊。对于数据库连接对象更是一知半解。

在学习VB.NET视频时,其中有几个单元讲到了.NET的数据库设计与连接。对于数据库的连接,其实我们并不陌生,原来在做红皮书和机房收费系统的时候,我们都有接触过,可是,在我的印象中,这些关于数据库连接的知识很是模糊。对于数据库连接对象更是一知半解。

回过头来,翻了一遍红皮书中的几个实例,里面讲到了利用ADO控件来连接数据库,它涉及到的数据库连接对象有7个(connection,command ,recordset,Field,Property,parameter,error)

那么对于如今学习的.net中数据库连接又涉及到了哪些对象呢?

其实,我们不难发现,无论是以前的ADO还是现在的.NET,在数据库连接中都存在两个永远不变的对象connection和command,那么在.net中它们是如何使用的呢?

1.Connection

数据库连接对象,负责连接数据库

具体使用:对于不同的数据提供者(provider)有不同的命名空间,但大体上都是一致的,如下所示以SQLserver为例:

Imports ss=System.Data.SqlClient '声明使用的命名空间

Dim sConn as string,dbConn as ss.SqlConnection
sConn="Server=localhost; Database=Dbname;integrated Security=SSPI" '连接字符串

dbConn=new ss.SqlConnection(sConn) '使用前实例化连接对象
dbConn.Open() '至此,就可以连接上数据库来对数据库中的数据进行操作了

2.Command

数据库命令对象,主要用来执行包括增加,删除,修改及查询等操作命令,也可用来执行预存储程序。

根据数据库提供者类型可将command对象分为四类分别是SqlCommand,OledbCommand,OdbcCommand,OracleCommand.

使用时,只需将它进行实例化即可

Dim ssCmd as ss.SqlCommand

ssCmd=new ss.SqlCommand(strSql,sConn) 'strSql为命令语句如select等,sConn为连接字符接上

当然,除此之外,command对象还有三个常用的方法:

ExecuteNonQuery():返回受影响的行数

ExecteScalar():从数据库中检索单个值,返回结果的第一行第一列

ExecuteReader():执行一个SQL语句,返回一个DataReader对象

谈到DataReader对象,这是什么意思呢?我们来介绍.net中的其余对象

3.DataReader

一个简单的数据集,用于从数据源中检索只读数据集,此对象在检索数据时,只允许只读、顺向方式读取数据,不能返回,同时,此对象可通过command对象中的ExecuteReader()方法从数据源中检索数据来创建。

它的read()方法用来读取下一条记录,若读到数据则返回TRUE,否则返回FALSE

在上述二者的基础上看看它的具体使用:

Dim ssReader as ss.SqlDataReader '和上面的command是一个道理

strSql="select * from Customers order by lastName ASC,firstName ASC;"

ssReader=ExecuteReader()'执行SQL指令

'开始读记录,下面firstName和lastName为两个列名,共组成一条记录,每循环一次,返回一条记录

do while ssReader.Read()

    Fn=System.Convert.ToString(ssReader("firstName"))

    In=System.Convert.ToString(ssReader("lastName"))

    me.listbox1.Items.Add(In,+ Fn)

loop

那么除此之外,在.设计.NET数据访问时,为了能够离线的对数据库进行操作,便将ADO数据连接中的Recordset对象用DataSet代替,来实现离线操作数据库的目的

在ADO中Recordset成为数据集对象,那么在.NET中的数据集对象就是DataSet了!

4.DataSet

通俗一点讲,其实就是一个离线的Recordset,用于离线处理数据,这是因为DataSet提供了一个离线的数据源(通常以表格形式显示),以减轻网络的负担。

\

如图所示,在DataSet的使用过程中,还需要借助于DataAdapter这个对象,那么DataAdapter在这里到底起什么作用呢?

其实,我们如果认真分析,如果DataSet在客户端想要进行离线处理,那么虽然说是自己来充当数据源,但是,如果它不和真正的数据源连接起来,那么最终还是起不到离线处理的效果。于是,我们必须在真正的数据源和DataSet之间建起一座桥梁,来使二者之间能够通信。那么这个桥梁就是DataAdapter,显然二者是不可分割的。我们来具体了解一下DataAdapter这个对象。

5.DataAdapter

.NET中的适配器对象,充当数据源和DataSet之间检索和保存数据的桥梁。那么他是如何实现二者之间的通信的呢?

首先,它通过数据库连接对象(connection)来连接数据源,其次,通过数据库命令对象(command)来使用规定的操作从数据源来检索数据将其送往DataSet,或从DataSet送往数据源。

通过上述介绍,对于DataSet和DataAdapter的具体功能有了一定的了解,那么二者是如何协调配合使用的呢?来看一个小例子:

仍然在上述connection和command部分代码的基础上进行操作:

Dim adapter as ss.SqlDataAdapter

Dim ds as System.Data.DataSet

’通过下面的程式码来讲数据源中的数据传到DataSet中

Sql="select * from Products;"

adapter=new ss.SqlDataAdapter(ssCmd) ’要传输的命令为ssCmd中的命令

ds=new System.Data.DataSet() '实例化dataset

ssConn.Open() '这里的open和close方法可省略,dataset会自动检查连接是否成功

Adapter.Fill(ds)

ssConn.Close()

’可利用下面的程式码来将dataset中的数据提取到listbox中

Ds.Tables("Table").TableName="Products"

Dim row as System.Data.DataRow,name as string

For each row in ds.Table("Products").Rows

       Name=convert.ToString(row.Item("ProductName"))

       Me.listBox1.Items.Add(name)

Next row

以上就是在.net视频中讲到的有关ado.net数据库连接中常用到的对象。通过了解这些对象的基本功能和用法,我们可以对.net数据库连接有更近一步的了解.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL's Role: Databases in Web ApplicationsMySQL's Role: Databases in Web ApplicationsApr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

MySQL: Building Your First DatabaseMySQL: Building Your First DatabaseApr 17, 2025 am 12:22 AM

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL: A Beginner-Friendly Approach to Data StorageMySQL: A Beginner-Friendly Approach to Data StorageApr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

Is MySQL Beginner-Friendly? Assessing the Learning CurveIs MySQL Beginner-Friendly? Assessing the Learning CurveApr 17, 2025 am 12:19 AM

MySQL is suitable for beginners because: 1) easy to install and configure, 2) rich learning resources, 3) intuitive SQL syntax, 4) powerful tool support. Nevertheless, beginners need to overcome challenges such as database design, query optimization, security management, and data backup.

Is SQL a Programming Language? Clarifying the TerminologyIs SQL a Programming Language? Clarifying the TerminologyApr 17, 2025 am 12:17 AM

Yes,SQLisaprogramminglanguagespecializedfordatamanagement.1)It'sdeclarative,focusingonwhattoachieveratherthanhow.2)SQLisessentialforquerying,inserting,updating,anddeletingdatainrelationaldatabases.3)Whileuser-friendly,itrequiresoptimizationtoavoidper

Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Apr 16, 2025 am 12:20 AM

ACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.

MySQL: Database Management System vs. Programming LanguageMySQL: Database Management System vs. Programming LanguageApr 16, 2025 am 12:19 AM

MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

MySQL: Managing Data with SQL CommandsMySQL: Managing Data with SQL CommandsApr 16, 2025 am 12:19 AM

MySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment