C# restore database and create user

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, 255this.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警告
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值