ICChip為Combobox.
自動檢測服務器上的數據庫是否存在某表和某字段,如果表不存在,先新建表,再在表下查詢某字段,如果不存在,則新建字段。
private void Database_Operation(ComboBox ICChip) { try { if (PubVar.SQL_Connection)//如果數據庫能打開 { using (SqlConnection conn = new SqlConnection(PubVar.connStr))//創建連接對象,並使用using釋放(關閉),連接用完后會被自動關閉 { //if (conn.State == ConnectionState.Open) conn.Close();//如果打開則先關閉 conn.Open(); // 打開數據庫連接 string sql = "select 1 from INFORMATION_SCHEMA.TABLES where TABLE_NAME='" + ICChip.Text.Trim() + "'"; SqlCommand command = new SqlCommand(sql, conn);//調用公共類中的ExceRead方法創建數據閱讀器 var Read = command.ExecuteScalar(); if (Read == null)//加個判斷,沒有則創建表 { sql = "create table [" + ICChip.Text.Trim() + "]([NO.] [int] identity(1,1))";//([NO.] [int] identity(1,1))";//創建表 //identity(1,1)自增ID using (SqlConnection Conn = new SqlConnection(PubVar.connStr)) { Conn.Open(); command = new SqlCommand(sql, Conn); command.ExecuteNonQuery(); } } //判斷字段是否存在 sql = "SELECT *FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + ICChip.Text.Trim() + "' AND COLUMN_NAME = '新字段'"; using (SqlConnection Conn = new SqlConnection(PubVar.connStr)) { Conn.Open(); command = new SqlCommand(sql, Conn); Read = command.ExecuteScalar(); } if (Read == null)//如果沒有字段則創建 { sql = "ALTER TABLE [" + ICChip.Text.Trim() + "] ADD [新字段] [text] null";//id int primary key IDENTITY(1,1) NOT NULL //創建字段 using (SqlConnection Conn = new SqlConnection(PubVar.connStr)) { Conn.Open(); command = new SqlCommand(sql, Conn); command.ExecuteNonQuery(); } } } } } catch (Exception ex) { MessageBox.Show("錯誤信息:" + ex.Message, "創建數據庫失敗!"); } }