SQL Server 2000DBAVisual Studio .NET 2003.NET 1.1Windows 2000Windows XP中级开发Visual StudioSQL ServerSQLWindows.NETC#
在 .NET 应用程序安装期间创建数据库 - 版本 1






4.25/5 (38投票s)
2005年8月27日
3分钟阅读

186533

4337
此应用程序可用于在 .NET 应用程序安装期间创建数据库、表和存储过程。
引言
在 .NET 应用程序安装期间创建数据库是一个常见需求。 我使用 SQL-DMO 和 .NET 设置项目中的自定义操作来实现这一点。 本文将向您展示如何创建数据库、表、存储过程和主键等。 虽然这里的表很简单,但您可以以同样的方式创建任意数量的表和存储过程。
使用演示应用程序
演示应用程序提供了所需的工具提示,这将帮助您使用该应用程序。
使用源代码
以下讨论了一些重要的函数
添加对 SQL-DMO 的引用
您可以通过在解决方案资源管理器中右键单击项目,然后选择“添加引用”,COM 组件和最新版本的“Microsoft SQLDMO 对象库”来执行此操作。
在声明部分创建应用程序和服务器对象
// Create an SQLDMO application
SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass();
// Create an Server, which resembles to your actual server
SQLDMO.SQLServer srv = new SQLDMO.SQLServerClass();
// Create Database
SQLDMO.Database nDatabase = new SQLDMO.Database();
// Create Data Files
SQLDMO.DBFile nDBFileData = new SQLDMO.DBFile();
// Create Log Files
SQLDMO.LogFile nLogFile = new SQLDMO.LogFile();
列出网络中可用的 SQL Server
此函数 fillCmbServerList()
列出网络中所有可用的服务器。 此函数不适用于单机。
private void fillCmbServerList()
{
try
{
// Create SQL Servers Collection
SQLDMO.NameList sqlServers =
sqlApp.ListAvailableSQLServers();
// Navigate through collection, one by one
for(int i=0;i<sqlServers.Count;i++)
{
object srv = sqlServers.Item(i + 1);
if(srv != null)
{
this.cmbServList.Items.Add(srv);
}
}
if(this.cmbServList.Items.Count > 0)
this.cmbServList.SelectedIndex = 0;
else
this.cmbServList.Text =
"<No available SQL Servers>";
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
列出服务器上可用的数据库
此代码块 btnData_Click
列出特定服务器上所有可用的数据库。 当您想要连接到现有数据库而不是安装新数据库时,这在 LAN 环境中非常有用。
private void btnData_Click(object sender,
System.EventArgs e)
{
try
{
/* Change the cursor to hour glass shape */
System.Windows.Forms.Cursor.Current=
System.Windows.Forms.Cursors.AppStarting;
if(rbLocal.Checked==true)
srv.Connect(this.txtServName.Text.Trim(),
this.txtUserName.Text,this.txtPass.Text);
else
srv.Connect(this.cmbServList.Text.Trim(),
this.txtUserName.Text,this.txtPass.Text);
// Navigate through each database in the
// server and add it to combo box
foreach(SQLDMO.Database db in srv.Databases)
{
if(db.Name!=null)
this.cmbDataName.Items.Add(db.Name);
}
if(this.cmbDataName.Items.Count!=0)
cmbDataName.SelectedIndex=0;
/* Change the cursor to default shape */
System.Windows.Forms.Cursor.Current =
System.Windows.Forms.Cursors.Default;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
srv.DisConnect();
}
}
在服务器上创建数据库
此函数 createDB()
将在指定的服务器上创建数据库和关联的文件。
// This function creates Database
private void createDB()
{
strDatabaseName = txtDBName.Text.ToString();
if (strDatabaseName == "")
{
MessageBox.Show("Enter the Name");
}
try
{
// Assign a name to database
nDatabase.Name = strDatabaseName;
// Assign a name to datafile
nDBFileData.Name = strDatabaseName;
nDBFileData.PhysicalName = srv.Registry.SQLDataRoot +
"\\DATA\\" + strDatabaseName + "_Data.mdf";
nDBFileData.PrimaryFile = true;
nDBFileData.Size = 2;
nDBFileData.FileGrowthType =
SQLDMO.SQLDMO_GROWTH_TYPE.SQLDMOGrowth_MB;
nDBFileData.FileGrowth = 1;
//Add the DBFile object
nDatabase.FileGroups.Item("PRIMARY").DBFiles.Add(nDBFileData);
// Assign name to Log files
nLogFile.Name = strDatabaseName + "Log";
nLogFile.PhysicalName = srv.Registry.SQLDataRoot +
"\\DATA\\" + strDatabaseName + "_Log.ldf";
nLogFile.Size = 2;
nDatabase.TransactionLog.LogFiles.Add(nLogFile);
srv.Databases.Add(nDatabase);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
在数据库中创建表
我们将讨论创建表的两种方法
- 此函数
tblEmployees()
将在数据库中创建一个表。 它还将在一个列上创建一个主键,并将默认值分配给一列。// This function creates a Table private void tblEmployees() { try { // Create a new Table SQLDMO.Table table = new SQLDMO.Table(); // Give Name to the Table table.Name="Employees"; // Create Columns for tables // Column 1 // Create new column SQLDMO.Column Col1 = new SQLDMO.Column(); // Give name to the column Col1.Name="EmpNo"; // Assign datatype to the column Col1.Datatype="int"; // Mention whether NULL values are allowed or not Col1.AllowNulls=false; // Column 2 SQLDMO.Column Col2 = new SQLDMO.Column(); Col2.Name="Name"; Col2.Datatype="varchar"; // Decide the length of varchar datatype Col2.Length=50; Col2.AllowNulls=false; // Column 3 SQLDMO.Column Col3 = new SQLDMO.Column(); Col3.Name="Surname"; Col3.Datatype="varchar"; Col3.Length=50; Col3.AllowNulls=true; // Column 4 SQLDMO.Column Col4 = new SQLDMO.Column(); Col4.Name="isPermanent"; Col4.Datatype="char"; Col4.Length=10; // Assign default value to the column Col4.DRIDefault.Text=strYes; Col4.AllowNulls=true; // Add Columns to the table table.Columns.Add(Col1); table.Columns.Add(Col2); table.Columns.Add(Col3); table.Columns.Add(Col4); // Create PRIMARY KEY SQLDMO.Key PK = new SQLDMO.Key(); PK.Clustered=true; PK.Type= SQLDMO.SQLDMO_KEY_TYPE.SQLDMOKey_Primary; // Add Primary Key to 'EmpNo' column PK.KeyColumns.Add("EmpNo"); // Add primary key to table table.Keys.Add(PK); // Add table to Database nDatabase.Tables.Add(table); } catch(Exception ex) { MessageBox.Show(ex.Message); } }
- 在这里,我们将使用存储过程
SP_Students
从脚本创建一个表。 我们将使用数据库的ExecuteImmediate
方法来执行存储过程。 成功创建表后,我们将从数据库中删除存储过程。 此代码写在 Install 按钮的 click 事件中。 代码如下// Execute the stored procedure to create table nDatabase.ExecuteImmediate("InsStudents",0,0); /* Remove the stored procedure from database. The index starts from 1.*/ nDatabase.StoredProcedures.Remove(2,"");
在数据库中创建存储过程
- 此函数
SP_Employees()
在数据库中创建存储过程// This function creates a Stored Procedure private void SP_Employees() { try { // Create a Stored Procedure SQLDMO.StoredProcedure strProc = new SQLDMO.StoredProcedure(); // Assign a name to stored procedure strProc.Name="InsEmployees"; // Write a Stored Procedure Script and pass it as a string. strProc.Text="CREATE procedure InsEmployees(" + "@v_EmpNo int,@v_Name varchar(50),@v_Surname varchar(50), @v_isPermanent char(10))"+ "as "+ "Begin Insert Into PersonalInfo(EmpNo,Name,Surname,isPermanent)"+ "values (@v_EmpNo,@v_Name,@v_Surname ,@v_isPermanent) end"; // Add the Stored Procedure to Database nDatabase.StoredProcedures.Add(strProc); } catch(Exception ex) { MessageBox.Show(ex.Message); } }
- 此函数
SP_Students()
是一个创建 Students 表的存储过程private void SP_Students() { try { // Create a Stored Procedure SQLDMO.StoredProcedure strProc = new SQLDMO.StoredProcedure(); // Assign a name to stored procedure strProc.Name="InsStudents"; // Write a Stored Procedure Script and // pass it as a string. strProc.Text="CREATE procedure InsStudents as begin create table Students(Name Varchar(50), Surname Varchar(50)) end"; // Add the Stored Procedure to Database nDatabase.StoredProcedures.Add(strProc); } catch(Exception ex) { MessageBox.Show(ex.Message); } }
如何在设置项目中使用此应用程序?
- 在解决方案资源管理器中,右键单击您的设置项目,然后选择 View --> Custom Actions
- 将打开“自定义操作”窗口
- 现在右键单击 Install,然后单击“添加自定义操作”
- 在将打开的对话框中,双击“应用程序文件夹”
- 在将打开的对话框中,单击“添加文件”按钮
- 在将打开的对话框中,导航到应用程序Release文件夹中的DBI.exe文件。 选择.exe文件,其他依赖项将自动添加
- 自定义操作编辑器将如下所示
- 选择刚刚添加的DBI.exe并按 F4 或打开“属性”窗口。 将
InstallerClass
属性设置为False
,如图所示。 默认情况下,InstallerClass
属性设置为True
其他注意事项
上面的代码可能会给出错误,提示“QueryInterface for interface SQLDMO.NameList failed”。 如果发生此类异常,则表示应使用最新的服务包(高于 SP 2)更新服务器。
历史
- 2005 年 9 月 3 日 - 第一次更新,使用脚本创建表。