动态创建数据库
??? 動態創建數據庫,就是不在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;
???}
??}
轉載于:https://www.cnblogs.com/ipointer/archive/2005/08/01/204476.html
總結
- 上一篇: 编写 Servlet 2.3 Filte
- 下一篇: 创建WebPart时的数据库连接问题。