动态创建数据库

    动态创建数据库,就是不在sql企业管理器中设计数据库,而是在程序中建库并建表。
    我原来对用程序操作数据库的概念总是先有一个跟数据库的连接,再用command对数据库操作。但这一次发现问题了,还没有我要创建的数

据库,我跟谁去连接呀。后来发现数据库中有个叫master的数据库,它是整个数据库系统的基础,首先我们可以跟它连接,然后创建我们的数

据库,之后再改变当前的数据库连接,用新建的数据库中进行之后的操作,比如建表,下面有一段C#代码,用于显示以上所述。
    还要提示的一点,我们可以把建表的一些sql语句放进一个txt文档,把它设为嵌入的资源,然后从程序集中读取这个sql语句。

  private string GetSql(string Name)
  {
   try
   {
    //Gets the current assembly.
    Assembly asm = Assembly.GetExecutingAssembly();

    //Resources are named using a fully qualified name.
    Stream strm = asm.GetManifestResourceStream(asm.GetName().Name+"."+Name);

    //Reads the contents of the embedded file.
    StreamReader reader= new StreamReader(strm);
    return reader.ReadToEnd();
   }
   catch(Exception ex)
   {
    throw ex;
   }
  }

  private void ExecuteSql(string DatabaseName,string Sql)
  {
   SqlCommand command = new SqlCommand(Sql,this.sqlConnection1);

   command.Connection.Open();
   command.Connection.ChangeDatabase(DatabaseName);
   try
   {
    command.ExecuteNonQuery();
   }
   finally
   {
    command.Connection.Close();
   }
  }

  protected void AddDBTable(string strDBName)
  {
   try
   {
    this.ExecuteSql("master","create database "+strDBName);
    this.ExecuteSql(strDBName,this.GetSql("sql.txt"));
   }
   catch(Exception ex)
   {
    throw ex;
   }
  }

posted on 2005-08-01 10:06  栖息的熊  阅读(749)  评论(0编辑  收藏  举报

导航