我正在开发一个应用程序,在其中创建数据库并使用c#和SMO部署一些表。
我能够成功创建数据库以及数据库中的所有表,而不会出现任何问题。我使用SQL脚本作为模板,并使用模板将表安装在新创建的数据库中。下面是我的代码。
public void CreateClientDatabase(string sDeployserver, string database)
{
SDeployServer = txtNbServer.Text.Trim().ToString();
string sConStr = string.Concat(Utilities.Decrypt(sEncDataSource), SDeployServer, Utilities.Decrypt(sCoreConn));
string sScriptText = "CREATE DATABASE " + database + string.Empty;
try
{
using(sqlConnection = new SqlConnection(sConStr))
{
ServerConnection svrConnection = new ServerConnection(sqlConnection);
Server server = new Server(svrConnection);
server.ConnectionContext.AutoDisconnectMode = AutoDisconnectMode.NoAutoDisconnect;
try
{
btnReset.Enabled = false;
btnExit.Enabled = false;
sqlConnection.Open();
server.ConnectionContext.ExecuteNonQuery(sScriptText);
}
catch (Exception ex)
{
MessageBox.Show(Resources.standard_error);
//RollbackDeployment(SDeployServer, database);
throw ex;
}
finally
{
sqlConnection.Close();
}
}
}
创建数据库后,我将使用以下代码部署表;我要做的是替换模板中的数据库名称,然后使用ExecuteNonQuery运行脚本
public void DeployCoreTable(string sConStr, string database, SqlConnection sqlConnection, string SDeployServer)
{
SScriptFile = string.Empty;
SUpdatedScript = string.Empty;
try
{
FileInfo file = new FileInfo(Path.GetFullPath(Application.StartupPath + "/scripts/core_script.sql"));
SScriptFile = file.OpenText().ReadToEnd();
SUpdatedScript = SScriptFile.Replace("db_project", database);
Server sUpdateServer = new Server(new ServerConnection(sqlConnection));
sUpdateServer.ConnectionContext.ExecuteNonQuery(SUpdatedScript);
lstInfo.Items.Add(Properties.Resources.coretable_success);
lstInfo.Refresh();
}
catch (Exception e)
{
lstInfo.Items.Add(Resources.coretable_error);
lstInfo.Items.Add(e);
lstInfo.Refresh();
MessageBox.Show(Resources.standard_error);
if (sqlConnection.State == ConnectionState.Open)
{
sqlConnection.Dispose();
sqlConnection.Close();
}
RollbackDeployment(SDeployServer, database);
}
}
一切正常,并且以相同的方式,我试图将现有的SQL登录名映射到新创建的数据库。下面是我用作模板的SQL脚本代码;
USE [db_project]
GO
/****** Object: User [acuitydbuser] Script Date: 02-04-2019 18:40:34 ******/
CREATE USER [dbuser] FOR LOGIN [dbuser] WITH DEFAULT_SCHEMA=[dbo]
GO
ALTER ROLE [db_owner] ADD MEMBER [dbuser]
GO
但是,当我从c#Windows Forms应用程序执行上述SQL文件时,出现一个错误,提示用户该数据库已经存在用户,因此失败了。
但是,我尝试了许多方法,但无法将现有的SQL登录名与新创建的数据库关联。谁能让我知道该怎么做?我需要在代码中进行修改吗?
我们非常感谢您的帮助。