动态创建数据库
??? 動(dòng)態(tài)創(chuàng)建數(shù)據(jù)庫(kù),就是不在sql企業(yè)管理器中設(shè)計(jì)數(shù)據(jù)庫(kù),而是在程序中建庫(kù)并建表。
??? 我原來(lái)對(duì)用程序操作數(shù)據(jù)庫(kù)的概念總是先有一個(gè)跟數(shù)據(jù)庫(kù)的連接,再用command對(duì)數(shù)據(jù)庫(kù)操作。但這一次發(fā)現(xiàn)問(wèn)題了,還沒(méi)有我要?jiǎng)?chuàng)建的數(shù)
據(jù)庫(kù),我跟誰(shuí)去連接呀。后來(lái)發(fā)現(xiàn)數(shù)據(jù)庫(kù)中有個(gè)叫master的數(shù)據(jù)庫(kù),它是整個(gè)數(shù)據(jù)庫(kù)系統(tǒng)的基礎(chǔ),首先我們可以跟它連接,然后創(chuàng)建我們的數(shù)
據(jù)庫(kù),之后再改變當(dāng)前的數(shù)據(jù)庫(kù)連接,用新建的數(shù)據(jù)庫(kù)中進(jìn)行之后的操作,比如建表,下面有一段C#代碼,用于顯示以上所述。
??? 還要提示的一點(diǎn),我們可以把建表的一些sql語(yǔ)句放進(jìn)一個(gè)txt文檔,把它設(shè)為嵌入的資源,然后從程序集中讀取這個(gè)sql語(yǔ)句。
??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;
???}
??}
轉(zhuǎn)載于:https://www.cnblogs.com/ipointer/archive/2005/08/01/204476.html
總結(jié)
- 上一篇: 编写 Servlet 2.3 Filte
- 下一篇: linux cmake编译源码,linu