vs2008 用脚本初始化数据库

原理:动态生成.DAT(批处理文件),根据。dat文件里面连接字符串来动态生成。然后dat来执行脚本。

 

 

static class Program
 {
  private static string _connectionFullString = "";
  private static string _connectionSimpleString = "";

  ///


  /// 完全连接字符串
  ///

  public static string connectionFullString
  {
   get { return _connectionFullString; }
   set { _connectionFullString = value; }
  }

  ///


  /// 简单连接字符串
  ///

  public static string connectionSimpleString
  {
   get { return _connectionSimpleString; }
   set { _connectionSimpleString = value; }
  }
  ///
  /// The main entry point for the application.
  ///

  [STAThread]

  ///
  ///数据库初始化
  ///
  #region
  public static void InitDatabase()
  {
   //用BAT文件调用sql初始化数据库
   try
   {
    //提示没有数据库,开始附加
    MessageBox.Show("程序检查到系统没有数据库LMS,点击确定开始附加数据库。", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
    string sqlScriptName = "LMS.sql";
    string strParaFileSql = Convert.ToString(AppDomain.CurrentDomain.BaseDirectory) + "LMS.sql";
    ComDB db = new ComDB();
    ComConfig config = new ComConfig();
    string connString = config.connectionSimpleString;
    string serverStr = "";
    string dbStr = "";
    string uidStr = "";
    string pwdStr = "";
    string strSec = "DBclient";
    string strParaFile = Convert.ToString(AppDomain.CurrentDomain.BaseDirectory) + "Rockey3.dat";

    serverStr = GetFromIniFile(strSec, "server", "", strParaFile);
    dbStr = GetFromIniFile(strSec, "database", "", strParaFile);
    uidStr = GetFromIniFile(strSec, "uid", "", strParaFile);
    pwdStr = GetFromIniFile(strSec, "pwd", "", strParaFile);
    System.AppDomainSetup t = new System.AppDomainSetup();
    t.ConfigurationFile = "ComLib.dll.config";
    _connectionFullString = "server=" + serverStr + ";database='" + dbStr + "';uid=" + uidStr + ";pwd=" + pwdStr;
    _connectionSimpleString = "server=" + serverStr + ";uid=" + uidStr + ";pwd=" + pwdStr;
    //删除这个目录的SqlDatabase.bat文件
    string delFile = "C://Program Files//优碧特软件//捷易管理系统旗舰版//SqlDatabase.bat";
    File.Delete(delFile);

    FileStream fs = new FileStream("C://Program Files//优碧特软件//捷易管理系统旗舰版//SqlDatabase.bat", FileMode.Append);
    StreamWriter sw = new StreamWriter(fs, Encoding.Default);
    //获得本机IP
    IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
    string myip = IpEntry.AddressList[0].ToString();
    //获得批处理文件内容
    string batFileText = "osql /S '" + myip + "' /U '" + uidStr + "' /P '" + pwdStr + "' /d '" + dbStr + "' /i  '" + sqlScriptName + "'";
    batFileText = batFileText.Replace("'", "/"").Replace("'", "“");
    //写批处理文件内容
    sw.Write(batFileText);
    sw.Close();
    fs.Close();
    //执行批处理文件
    System.Diagnostics.Process pExecuteEXE = new System.Diagnostics.Process();
    string targetdirParm = System.Windows.Forms.Application.StartupPath.Replace(" ", "@");
    //string b = System.Windows.Forms.Application.StartupPath + "//SqlDatabase.bat";//bat文件地址
    //string c =fs.Name;
    pExecuteEXE.StartInfo = new System.Diagnostics.ProcessStartInfo(fs.Name, targetdirParm);
    pExecuteEXE.Start();
    pExecuteEXE.WaitForExit();

    return;
   }
   catch (Exception ex)
   {
    MessageBox.Show(ex.Message);
    return;
   }
  }
  #endregion
  #region 获取 配置文件中的连接串

  
  public static string GetFromIniFile(string SectionName, string KeyName, string Defaults, string FileName)
  {

   StringBuilder strValue = new StringBuilder(500);
   int rtn;
   rtn = GetPrivateProfileString(SectionName, KeyName, "ConnectionErr", strValue, 500, FileName);

   return strValue.ToString();
  }

  [DllImport("kernel32")]
  private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

  #endregion
  [WebMethod(Description = "取得更新版本")]
  static string GetVer()
  {
   XmlDocument doc = new XmlDocument();
   doc.Load(HttpContext.Current.Server.MapPath("update.xml"));
   XmlElement root = doc.DocumentElement;
   return root.SelectSingleNode("version").InnerText;
  }
  ///


  /// 创建数据库
  ///

  #region 数据库安装及还原
  public static void CreateDatabase()
  {
   ComDB db = new ComDB();
   string strSql = "CREATE DATABASE " + "LMS";
   ComConfig config = new ComConfig();
   string connString = config.connectionSimpleString;
   if (config.connectionSimpleString == "")
   {
    MessageBox.Show("请确定ROKET3.DAT文件是否存在!", "数据库连接", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    return;
   }

   SqlConnection con = new SqlConnection(connString);
   SqlCommand cmd = new SqlCommand(strSql, con);
   DataSet ds = new DataSet();
   try
   {
    con.Open();
    //dt = db.DbDataTable(strSql, "Test");
    SqlDataAdapter command = new SqlDataAdapter(strSql, con);
    command.Fill(ds, "LMS");
   }
   catch (System.Data.SqlClient.SqlException E)
   {
    //throw new Exception(E.Message);
    MessageBox.Show(E.Message);
    return;
   }
   finally
   {
    con.Close();
   }
  }
  #endregion
  static void Main()
  {
   if (!CheckDataBaseExist())
   {
    CreateDatabase();
    InitDatabase();
   }
   Application.EnableVisualStyles();
   Application.SetCompatibleTextRenderingDefault(false);
   Application.Run(new Form1());

  }
  #region 判断初始数据库是否存在
  public static bool CheckDataBaseExist()
  {
   ComDB db = new ComDB();
   string strSql = "select   *   from sysdatabases   where   [name]   = 'LMS'";
   ComConfig config = new ComConfig();
   string connString = config.connectionSimpleString;
   if (config.connectionSimpleString == "")
   {
    MessageBox.Show("请确定ROKET3.DAT文件是否存在!", "数据库连接", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    return false;
   }
   SqlConnection con = new SqlConnection(connString);
   SqlCommand cmd = new SqlCommand(strSql, con);
   DataSet ds = new DataSet();
   try
   {
    con.Open();
    //dt = db.DbDataTable(strSql, "Test");
    SqlDataAdapter command = new SqlDataAdapter(strSql, con);
    command.Fill(ds, "LMS");
   }
   catch (System.Data.SqlClient.SqlException E)
   {
    //throw new Exception(E.Message);
    MessageBox.Show(E.Message);
    return false;
   }
   finally
   {
    con.Close();
   }
   if (ds.Tables[0].Rows.Count > 0)
   {
    return true;
   }
   else
   {
    return false;
   }
  }
  #endregion
 }

你可能感兴趣的:(脚本,string,dataset,数据库,exception,database)