C#對(duì)SQL Server數(shù)據(jù)庫(kù)連接,增,刪,改,查示例代碼
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
using System; using System.Collections.Generic; using System.Web; using System.Data.OleDb; using System.Data; using System.Data.SqlClient; //數(shù)據(jù)庫(kù)連接字符串(四個(gè)參數(shù),數(shù)據(jù)庫(kù)服務(wù)器名稱,連接的數(shù)據(jù)庫(kù)名稱,登陸賬號(hào)和密碼) string strconnection = "Data Source=****;Initial Catalog=****;User ID=sa ;password=******";//查 SqlDataAdapter sda = new SqlDataAdapter("select語(yǔ)句", strconnection);//該對(duì)象會(huì)自動(dòng)打開(kāi)并連接數(shù)據(jù)庫(kù) DataSet ds = new DataSet(); sda.Fill(ds); DataTable dt = ds.Tables[0];//數(shù)據(jù)存在dt中 SqlConnection conn = new SqlConnection(strconnection);//連接對(duì)象 if (conn.State == ConnectionState.Closed)//打開(kāi)連接,如果沒(méi)有該句,在數(shù)據(jù)庫(kù)關(guān)閉情況下會(huì)出現(xiàn)異常 { conn.Open(); } SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "SQL語(yǔ)句"; cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery();//返回一個(gè)大于0的數(shù),則執(zhí)行成功,根據(jù)需要,可以對(duì)返回值做個(gè)判斷 if (conn.State == ConnectionState.Open)//關(guān)閉連接 { conn.Close(); } 該文章在 2021/1/30 11:36:19 編輯過(guò) |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |