Create Database Programmatically
I am trying to create a database programmatically in C#. I have scripts for database creation which work fine when I run them from SQL Server Management Studio. However, when I run the same scripts from my C# application, the following error occurs:
An unhandled exception of type '开发者_Python百科Microsoft.SqlServer.Management.Common.ExecutionFailureException' occurred in Microsoft.SqlServer.ConnectionInfo.dll
Any ideas as to why this might be happening?
Just to let you know there is a c# frame work which will do all this for you. http://www.sharparchitecture.net/ it will build your DB and your data access layer from a OO model.
public string CreateDataBase(string ipAddress, string UserName, string Password,string DB_filepath) {
Microsoft.SqlServer.Management.Smo.Server addDBserver = new Microsoft.SqlServer.Management.Smo.Server(ipAddress);
addDBserver.ConnectionContext.LoginSecure = false;
addDBserver.ConnectionContext.Login = UserName;
addDBserver.ConnectionContext.Password = Password;
try
{
//*Crerate Databse*
addDBserver.ConnectionContext.Connect();
FileInfo filedb = new FileInfo(DB_filepath);
string scriptdb = filedb.OpenText().ReadToEnd();
string scriptdb1 = scriptdb.Replace("GO", Environment.NewLine);
string scriptdb2 = scriptdb1.Replace("\r\nGO\r\n", "");
addDBserver.ConnectionContext.ExecuteNonQuery(scriptdb2);
addDBserver.ConnectionContext.Disconnect();
string Msg;
Msg = "db created successfully";
return Msg;
return true;
}
catch (Exception ex)
{
string Msg1 = "db notcreated successfully";
return ex.Message;
throw;
}
}
//Database created Successfully
精彩评论