C#操作sql server

來源:互聯網
上載者:User

標籤:oca   移除   開始   int   each   remove   中心   取數   form   

C#操作sqlserver跟操作其他資料沒有太大差別,但是又一些細節要注意一下。

在安裝sqlserver時不要選擇預設執行個體,如果是則需要更改設定,還有遠端連線要去串連服務中設定一下,如連接埠1433等,這些百度一下就可以了。下面開始介紹一些最基本的資料庫操作。

(一)建立資料庫

        static void SQLDBCreate(string dbname)        {            //通過串連到本身存在的db  master串連到sqlserver            string connStr = "Server = localhost;User Id=sa;Password=******; database = master";            SqlConnection conn = new SqlConnection(connStr);            conn.Open();            //如果當前資料庫是正在狀態是無法刪除的,所以把master設定為目前狀態,若資料庫存在則刪除重建            //此處出問題一般為資料安裝過程中為預設執行個體,改為特定執行個體,然後啟動服務中心,在ip3更改相關ip為本機,並把tcp連接埠改為1433            //其他更改為是,同時在服務中restart即可以            string sql= "use master;" +            "IF DB_ID(N‘{0}‘) IS NOT NULL " +            "DROP DATABASE {0};" +                "CREATE DATABASE {0}";            sql = string.Format(sql, dbname);            try            {                SqlCommand cmd = new SqlCommand(sql, conn);                cmd.ExecuteNonQuery();                Console.WriteLine("createdb_success");            }            catch (Exception ex)            {                Console.WriteLine("createdb_failed:"+ex.Message);            }            finally            {                conn.Close();            }        }

(二)在建立的資料庫中建表

        static void TableCreate(string dbname,string tablename)        {            string connStr = "Server = localhost;User Id=sa;Password=********; database = {0}";            connStr = string.Format(connStr, dbname);            string sql= "IF OBJECT_ID(N‘{1}..{0}‘, N‘U‘) IS NOT NULL " +                 "DROP TABLE {0};" +                "CREATE TABLE {0}" +                "(ID [int] NOT NULL Primary Key," +                "Name [char] (40) NULL ," +                "Price [char] (40) NULL," +            "dPrice [char] (40) NULL)";            sql = string.Format(sql, tablename, dbname);            SqlConnection conn = new SqlConnection(connStr);            conn.Open();            try            {                SqlCommand cmd = new SqlCommand(sql, conn);                cmd.ExecuteNonQuery();                Console.WriteLine("createtable_success");            }            catch(Exception ex)            {                Console.WriteLine("createtable_failed:" + ex.Message);            }            finally            {                conn.Close();            }        }

(三)想表中添加資料

        static void FillTable(string dbname,string tablename)        {            string connStr = "Server = localhost;User Id=sa;Password=********; database = {0}";            connStr = string.Format(connStr, dbname);            SqlConnection conn = new SqlConnection(connStr);            conn.Open();            string sql= "INSERT INTO {0}(ID,name,price,dPrice)" +                "values(@d,@a,@b,@c)";            sql = string.Format(sql, tablename);            try            {                for(int i=0;i<100;i++)                {                    SqlCommand cmd = new SqlCommand(sql, conn);                    cmd.Parameters.AddWithValue("@d", i);                    cmd.Parameters.AddWithValue("@a", Guid.NewGuid());                    cmd.Parameters.AddWithValue("@b", i.ToString());                    cmd.Parameters.AddWithValue("@c", i.ToString());                    cmd.ExecuteNonQuery();                                    }                Console.WriteLine("filltable_success");            }            catch(Exception ex)            {                Console.WriteLine("filltable_failed:" + ex.Message);            }            finally            {                conn.Close();            }        }

(四)刪除表格

        static void DeleteTable(string dbname,string tablename)        {            string connStr = "Server = localhost;User Id=sa;Password=*********; database = {0}";            connStr = string.Format(connStr, dbname);            SqlConnection conn = new SqlConnection(connStr);            conn.Open();            string sql= "IF OBJECT_ID(N‘{0}..{1}‘, N‘U‘) IS NOT NULL " +                 "DROP TABLE {1};";            sql = string.Format(sql, dbname, tablename);            try            {                SqlCommand cmd = new SqlCommand(sql, conn);                cmd.ExecuteNonQuery();                Console.WriteLine("deletetable_success");            }            catch(Exception ex)            {                Console.WriteLine("deletetable_failed:" + ex.Message);            }            finally            {                conn.Close();            }        }

(五)讀取資料庫中資料

        static void TransToDS(string dbname,string tablename)        {            string connStr = "Server =.;User Id=sa;Password=*******; database = {0}";            connStr = string.Format(connStr, dbname);            SqlConnection conn = new SqlConnection(connStr);            conn.Open();            string sql = "select *from {0}";            sql = string.Format(sql, tablename);            SqlCommand cmd = new SqlCommand(sql, conn);            SqlDataAdapter apt = new SqlDataAdapter(cmd);            SqlCommandBuilder sb = new SqlCommandBuilder(apt);            DataSet ds = new DataSet();                        try            {                                apt.Fill(ds);                Console.WriteLine("transTods_success");            }            catch (Exception ex)            {                Console.WriteLine("transTods_failed:" + ex.Message);            }            finally            {                conn.Close();            }            DataTable dt = ds.Tables[0];            //int i = 0;            //foreach(DataRow dr in ds.Tables[0].Rows)            //{            //    if(i>50)            //    {            //        ds.Tables[0].Rows.RemoveAt(i);            //    }            //    i++;            //}            int count = dt.Rows.Count;            for(int i=0;i<count;i++)            {                if(i>50)                {                    //dt.Rows.RemoveAt(51);                    dt.Rows[i].Delete();                }            }            apt.Update(ds);                       int j = 0;            foreach (DataRow dr in ds.Tables[0].Rows)            {                Console.WriteLine(dr["Price"]+" "+j+" "+dr.RowState);                j++;            }                 }

關於資料操作在此多說一點,可以用sqldatareader進行讀取,插入修改資料等也可以採用insert等方法進行處理,在此採用dataset先把資料表緩衝到本地表中進行操作,如果只需要。看需要自己選擇,採用dataset包括更新資料表等都很方便,只需要用sqldataadapter進行一下update就可以。

注意:

1、在對datatable進行遍曆並進行刪除操作時,不要用foreach,其不允許進行增加和刪除

2、如果資料表需要update,那麼資料表進行增刪是要用add和delete,不要用import和remove,因為在進行update時,是根據datarow的rowstate屬性進行操作的。比如delete時,並不是刪除row,而是把相應行的rowstate進行了修改,update時就根據此屬性進行處理,本機資料表只有當採用acceptchange時才會根據rowstate屬性進行資料表的相應刪除。而採用import或者remove時則rowstate屬性則會存在問題,比如採用remove時,整行移除後相應的rowstate也不存在,而update時,由於相應的行沒有rowstate屬性值,所以遠端資料庫不會進行刪除。import倒入後rowstate狀態不明,所以也無法進行遠端資料庫的資料更新。

總之,採用update時並不是拿本地datatable與sqlserver資料表進行對比然後更新,而是根據datatable中的datarow的rowstate屬性直接修改sqlserver資料表。

 

C#操作sql server

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.