您的位置:首页 > 编程语言 > C#

C# restore database and create user

2007-01-08 11:03 197 查看

using System;


using System.IO;


using System.Runtime.InteropServices;


using System.Text;


using System.Data.SqlClient;


using System.Data;


namespace RestoreDatabase




...{


public class IniFile




...{


private string bakFileName = string.Empty;


private string bakfileNmNotExtension = string.Empty;


public string Path;




/**/////声明读写INI文件的API函数


[DllImport("kernel32")]


private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);


[DllImport("kernel32")]


private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);




//类的构造函数,传递INI文件名


public IniFile(string inipath)




...{


Path = inipath;


}




//写INI文件


public void IniWriteValue(string Section, string Key, string Value)




...{


WritePrivateProfileString(Section, Key, Value, this.Path);


}




//读取INI文件指定


public string IniReadValue(string Section, string Key)




...{


StringBuilder temp = new StringBuilder(255);


int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.Path);


return temp.ToString();


}


public string bakFileNm




...{




get ...{ return this.bakFileName; }




set ...{ this.bakFileName = value; }


}


public string bakFileNmNotExn




...{




get ...{ return this.bakfileNmNotExtension; }




set ...{ this.bakfileNmNotExtension = value; }


}


public Boolean JudgementNotExist(string sql, string tableNm,ref SqlConnection conn, ref DataSet ds, ref SqlDataAdapter da)




...{


try




...{


ds.Tables.Clear();


da.SelectCommand = new SqlCommand(sql,conn);


da.Fill(ds, tableNm);


if (ds.Tables[0].Rows.Count == 0)


return true;


else


return false;


}


catch (Exception e)




...{ throw e; }


}


}


}



Program.cs


using System;


using System.Collections.Generic;


using System.Text;


using System.Data.SqlClient;


using System.Data;


using System.Reflection;


using System.IO;




namespace RestoreDatabase




...{


class Program




...{


public static void Main(string[] args)




...{


string ServerName, MSSQLDB, UsrId, UsrPwd, InifilePath, SysPath, ExistDBsql, restoreSql, CreateDBSql;


string CreateLogin, CreateUser, CreateAlter, AddRole, ExistLogins,ExistUser;




try




...{


//get database info from 'database.ini' file


InifilePath = Environment.CurrentDirectory + "/Setup/Database/databaseInfo.ini";


IniFile ini = new IniFile(InifilePath);


//ServerName = ini.IniReadValue("Database", "ServerName");


MSSQLDB = ini.IniReadValue("Database", "MSSQLDB");


UsrId = ini.IniReadValue("Database", "USRID");


UsrPwd = ini.IniReadValue("Database", "USRPWD");


//get '.bak' file from currentDirectory


DirectoryInfo dir = new DirectoryInfo(Environment.CurrentDirectory + "/Setup/Database/");


foreach (FileInfo fileinfo in dir.GetFiles("*.bak"))




...{


if (fileinfo.Extension == ".bak")




...{


ini.bakFileNm = fileinfo.Name;


ini.bakFileNmNotExn = fileinfo.Name.Replace(fileinfo.Extension, "").Trim();


}


}


SysPath = Environment.CurrentDirectory + "/Setup/Database/" + ini.bakFileNm;


ExistDBsql = "SELECT 1 FROM master..sysdatabases WHERE name='" + ini.bakFileNmNotExn + "'";


restoreSql = "RESTORE DATABASE " + MSSQLDB + " FROM DISK='" + SysPath + "' WITH REPLACE";


CreateDBSql = "CREATE DATABASE " + MSSQLDB + " ";


CreateLogin = "EXEC master.dbo.sp_addlogin @loginame = N'" + UsrId + "', @passwd = N'" + UsrPwd + "'";


//CreateLogin = "CREATE LOGIN [" + UsrId + "] WITH PASSWORD=N'" + UsrPwd + "', DEFAULT_DATABASE=[master], " +


// "DEFAULT_LANGUAGE= [us_english], CHECK_EXPIRATION=ON, CHECK_POLICY=ON ";


CreateUser = "CREATE USER [" + UsrId + "] FOR LOGIN [" + UsrId + "] ";


CreateAlter = "ALTER USER [" + UsrId + "] WITH DEFAULT_SCHEMA=[dbo] ";


AddRole = "EXEC sp_addrolemember N'db_owner', N'" + UsrId + "' ";


ExistLogins = "SELECT 1 FROM master..syslogins where name='" + UsrId + "'";


ExistUser="select * from sysusers where name='" + UsrId + "'";




SqlConnection conn = new SqlConnection("server=localhost;uid=sa;pwd=as;");


SqlCommand comm = new SqlCommand();


comm.Connection = conn;


conn.Open();


DataSet ds = new DataSet();


SqlDataAdapter da = new SqlDataAdapter(ExistDBsql, conn);


if (ini.JudgementNotExist(ExistDBsql, "sysdatabases", ref conn, ref ds, ref da))




...{


Console.WriteLine("Creating Database...");


comm.CommandText = CreateDBSql;


comm.ExecuteNonQuery();


Console.WriteLine("Create Database Complete.");


}


Console.WriteLine("Restoring Database...");


comm.CommandText = restoreSql;


comm.ExecuteNonQuery();


Console.WriteLine("Restore Database Complete.");




Console.WriteLine("Creating Database User ...");


comm.Connection.ChangeDatabase("master");


if (ini.JudgementNotExist(ExistLogins, "sysdatabases", ref conn, ref ds, ref da))




...{


comm.CommandText = CreateLogin;


comm.ExecuteNonQuery();


}


comm.Connection.ChangeDatabase(ini.bakFileNmNotExn);


if (ini.JudgementNotExist(ExistUser, "sysdatabases", ref conn, ref ds, ref da))




...{


comm.CommandText = CreateUser;


comm.ExecuteNonQuery();


comm.CommandText = CreateAlter;


comm.ExecuteNonQuery();


comm.CommandText = AddRole;


comm.ExecuteNonQuery();


}


Console.WriteLine("Create Database User Complete");


}


catch (Exception e)




...{


Console.WriteLine(e.ToString());


Console.WriteLine();


Console.WriteLine("We are sorry for the inconvenience caused to you.");


Console.WriteLine("You will receive an email from us to help you find what you need.");


Console.ReadLine();


}


}






}


}



PS:注意,因为CommadTimeOut(即等待命令执行的时间)默认为30秒,如果你的数据库足够大的话,必须重新设置该值。不然将出现TimeOut警告
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: