Home Database Mysql Tutorial .NET数据库连接中的对象

.NET数据库连接中的对象

Jun 07, 2016 pm 03:56 PM
.net study object database video connect

在学习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() '至此,就可以连接上数据库来对数据库中的数据进行操作了
Copy after login

2.Command

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

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

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

Dim ssCmd as ss.SqlCommand

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

当然,除此之外,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
Copy after login

那么除此之外,在.设计.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
Copy after login

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

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

iPhone camera flickers/flickers in room lights: fix iPhone camera flickers/flickers in room lights: fix Jun 06, 2024 pm 02:28 PM

Does your iPhone camera flicker or flicker too much in indoor lights? Videos you shoot with your iPhone won't look good because the lights will be on. The flicker you see on your video is because of the difference in refresh rates. This is not normal and there are ways to fix this. This fix will help you solve the continuous flickering or flickering effect in iPhone videos. Fix – Change Video Output Format The reason behind this phenomenon is the apparent difference between the refresh rate of the object and the camera lens. Usually, if you use iPhone to record your screen, the video will flicker or flicker a lot. However, if you record a normal video, it shouldn't flicker. This phenomenon is mainly due to the mismatch between the refresh rate of the screen and the frame rate of the camera. The screen refresh rate is usually

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP Database Connection Pitfalls: Avoid Common Mistakes and Misunderstandings PHP Database Connection Pitfalls: Avoid Common Mistakes and Misunderstandings Jun 05, 2024 pm 10:21 PM

To avoid PHP database connection errors, follow best practices: check for connection errors and match variable names with credentials. Use secure storage or environment variables to avoid hardcoding credentials. Close the connection after use to prevent SQL injection and use prepared statements or bound parameters.

See all articles