面向对象在数据库应用程序中的应用(dotNet)
面向对象在数据库应用程序中的应用 (dotNet) 现在的应用程序很大一部分都是与数据库相关的程序,而写数据库程序会涉及到很多数据表,访问和操纵数据表构成了数据库应用程序最常见的动作,所以,编写出高效的程序对于程序员来说是不得不去考虑的。本文将讨论
面向对象在数据库应用程序中的应用(dotNet)
现在的应用程序很大一部分都是与数据库相关的程序,而写数据库程序会涉及到很多数据表,访问和操纵数据表构成了数据库应用程序最常见的动作,所以,编写出高效的程序对于程序员来说是不得不去考虑的。本文将讨论这个话题,希望对读者朋友有所裨益。
面向对象是当今程序界的普遍编程思想,他具有三个最基本的特征:封装、继承和多态。继承对于代码的复用非常有效,多态则是指函数(方法)的多种形态,可以通过子类重写父类的方法来改变对象的行为,在面向对象编程中起到非常重要的作用。那么,在实际应用中,到底能起到什么样的作用呢?也许使用例子最能表达这个思想。
比如,我们要写一个简单的论坛程序,经过分析,可以得出需要下面的表:用户表(Users)、版块表(BBSBlock)、回复表(Reply)、主题表(Topic)等(为了方便代码的继承,我把所有表的id号都设成相同的名称:id)。对于这些表,都有一些相同的操作:浏览,删除,添加和修改。那么,我们是不是对每个表都写对应的方法来实现呢?显示,这种方法是笨拙的。而继承,在这里就会发挥极为重要的作用。思想是:写一个父类,把这些基本的操作写好,然后,将每个表抽象成一个类,并继承刚才创建的父类,此时,所有的子类都具有这些基本操作了。
我们可以这样定义父类:
public class DBBaseClass
{
protected string TableName;//表名
protected SqlConnection con;//连接对象
public DBBaseClass():this("Users")
{
}
///
/// 构造函数
///
/// 表名
public DBBaseClass(string TableName)
{
this.TableName = TableName;
if(con == null)
{
con = new SqlConnection("server=accp-lzh;database=MissBBS;uid=sa;pwd=sa");
}
else
{
if(con.State == ConnectionState.Open)
con.Close();
}
}
///
/// 获取数据集
///
/// 如果count为0,则获取所有数据集,否则获取指定条数(从顶部)的记录
///
public DataSet Select(int count)
{
string sql;
if(count == 0)
sql = "select * from " + this.TableName ;
else
sql = "select top " + count.ToString() + " * from " + this.TableName + " oreder by id desc";
SqlCommand selectCmd = new SqlCommand(sql,con);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = selectCmd;
DataSet ds = new DataSet();
try
{
con.Open();
adapter.Fill(ds,"BBSTable");
con.Close();
}
catch(Exception)
{
return null;
}
return ds;
}
}
在这个类中,我们定义了两个重载的构造函数和一个用来获取数据集的方法,同时,定义了两个作用很大的字段,一个是表名,一个是连接对象。当其他类继承这个类时,就不再需要再次定义表和连接对象了,最主要是的,这两个字段为我们更好的实现继承起到了关键的作用。
接下来,我们创建一个子类:Users。这个类是表Users的抽象:
public class User : DBBaseClass
{
///
/// 无参构造函数
///
public User():base("Users")
{
}
///
/// 构造函数
///
/// 表名
public User(string TableName) : base(TableName)
{
}
}
现在,大家可以看出来,我们只是写了该类的两个构造函数,就具有返回表中所有数据集的功能了,因为该表继承了DBBaseClass。
同样,我们再写一个子类:Topic,该类是表Topic的抽象。
public class Topic : DBBaseClass
{
public Topic() : base("Topic")
{
}
public Topic(string TableName) : base(TableName)
{
}
}
和User一样,该类也同样具有了返回所有数据集的功能。
实例化子类时,采用简单对象工厂设计模式,返回不同类型的对象。
public class Factory
{
public Factory()
{
}
public static DBBaseClass GetObject(string TableName)
{
switch(TableName)
{
case "Users" :
return new User();
case "Topic":
return new Topic();
case "BBSBlock":
return new BBSBlock();
case "Reply":
return new Reply();
case "BBSMaster":
return new BBSMaster();
default:
return new DBBaseClass();
}
}
}
下面来看一看如何使用:
User user = (User)Factory.GetObject("Users");
DataSet ds1 = new DataSet();
ds1 = user.Select(0);
Topic topic = (Topic)Factory.GetObject("Topic");
DataSet ds2 = new DataSet();
ds2 = topic.Select(0);
看完之后,您有什么想法?如果您是一个经验丰富的程序员,这种方法肯定会经常采用,如果您刚刚接触,理解这种思想还是大有好处的。
posted on 2004年08月19日 3:28 PM

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Having issues with the Shazam app on iPhone? Shazam helps you find songs by listening to them. However, if Shazam isn't working properly or doesn't recognize the song, you'll have to troubleshoot it manually. Repairing the Shazam app won't take long. So, without wasting any more time, follow the steps below to resolve issues with Shazam app. Fix 1 – Disable Bold Text Feature Bold text on iPhone may be the reason why Shazam is not working properly. Step 1 – You can only do this from your iPhone settings. So, open it. Step 2 – Next, open the “Display & Brightness” settings there. Step 3 – If you find that “Bold Text” is enabled

Deleted something important from your home screen and trying to get it back? You can put app icons back on the screen in a variety of ways. We have discussed all the methods you can follow and put the app icon back on the home screen. How to Undo Remove from Home Screen in iPhone As we mentioned before, there are several ways to restore this change on iPhone. Method 1 – Replace App Icon in App Library You can place an app icon on your home screen directly from the App Library. Step 1 – Swipe sideways to find all apps in the app library. Step 2 – Find the app icon you deleted earlier. Step 3 – Simply drag the app icon from the main library to the correct location on the home screen. This is the application diagram

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

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 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())

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.

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

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.
