C# SQLserver 查詢表和字段是否存在,不存在則新建


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, "創建數據庫失敗!");
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM