C# SQLserver 查詢表和欄位是否存在,不存在則新建
阿新 • • 發佈:2021-12-21
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, "建立資料庫失敗!"); } }