/// <summary>
/// 创建数据库。
/// </summary>
/// <param name="srvName">表示要连接的服务器名</param>
/// <param name="dbName">指定要创建的数据库名</param>
private string CreateDB(string srvName, string dbName)
{
SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass();
SQLDMO.SQLServer srv = new SQLDMO.SQLServerClass();
srv.Connect(srvName, "sa", "");
// 新建数据库名(包括路径)
string dbPath = srv.Registry.SQLDataRoot + "//DATA//" + dbName;
bool DBExist = false;
foreach (SQLDMO.Database db in srv.Databases)
{
if (db.Name == dbName)
{
DBExist = true;
}
}
//函数返回结果
string rvCDB;
if (DBExist)
{
rvCDB = "此数据库存名已存在请选择其它名称";
srv.Close();
sqlApp.Quit();
return rvCDB;
}
else
rvCDB = "成功创建数据库!";
SQLDMO.Database nDB = new SQLDMO.Database();
SQLDMO.DBFile nDBFile = new SQLDMO.DBFile();
SQLDMO.LogFile nLogFile = new SQLDMO.LogFile();
nDB.Name = dbName;
nDBFile.Name = dbName + "file";
nDBFile.PhysicalName = dbPath + "_Data.mdf";
nDBFile.PrimaryFile = true;
nDBFile.FileGrowthType = 0;
nDBFile.FileGrowth = 1;
nDB.FileGroups.Item("primary").DBFiles.Add(nDBFile);
nLogFile.Name = dbName + "log";
nLogFile.PhysicalName = dbPath + "_Log.ldf";
nDB.TransactionLog.LogFiles.Add(nLogFile);
srv.Databases.Add(nDB);
srv.Close();
sqlApp.Quit();
return rvCDB;
}
SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass();
SQLDMO.SQLServer srv = new SQLDMO.SQLServerClass();
srv.Connect("servername", "username", "password");
SQLDMO.Database nDB = new SQLDMO.Database();
SQLDMO.DBFile nDBFile = new SQLDMO.DBFile();
SQLDMO.LogFile nLogFile = new SQLDMO.LogFile();
nDB.Name = "tmpdb"; //数据库名
nDBFile.Name = "tmpfile"; //数据库文件名
nDBFile.PhysicalName = @"e:/temp/tmp.mdf"; //数据库文件在硬盘上存储的实际名称
nDBFile.PrimaryFile = true;
nDBFile.FileGrowthType = 0;
nDBFile.FileGrowth = 1;
nDB.FileGroups.Item("primary").DBFiles.Add(nDBFile);
nLogFile.Name = "tmplg";
nLogFile.PhysicalName = @"e:/temp/tmp.ldf";
nDB.TransactionLog.LogFiles.Add(nLogFile);
srv.Databases.Add(nDB);
srv.Close();
sqlApp.Quit();
相关网址:http://www.codeproject.com/cs/database/DBInstaller.asp?target=SQLDMO