如何利用C#通過sql語句操作Sqlserver數(shù)據(jù)庫教程
必要準(zhǔn)備
你得有一個sqlserver數(shù)據(jù)庫,并且要和vs項目連接。
關(guān)于VS連接sqlserver數(shù)據(jù)庫的教程前幾天發(fā)過了,鏈接如下
VS2022連接sqlserver數(shù)據(jù)庫教程
調(diào)用用于訪問和控制數(shù)據(jù)庫的程序集。還得確保你真的安裝了這個程序集
using System.Data.SqlClient;
安裝好如下才對
填寫連接參數(shù)字符串
無賬號密碼的數(shù)據(jù)庫服務(wù)器(windows用戶認證)這樣寫即可
string connStr = "Data Source=LAPTOP-82MUPKTO;Initial Catalog=CSDN予我心安A3的數(shù)據(jù)庫;Integrated Security=True"; //LAPTOP-82MUPKTO 連接的數(shù)據(jù)庫服務(wù)器名 //CSDN予我心安A3的數(shù)據(jù)庫 連接的數(shù)據(jù)庫名
有賬號密碼登錄的數(shù)據(jù)庫服務(wù)器(sqlserver身份認證)這樣寫
string connStr = "Data Source=服務(wù)器名;Initial Catalog=數(shù)據(jù)庫名;User ID = 賬號;Password=密碼";
將連接參數(shù)字符串傳入數(shù)據(jù)庫鏈接類,生成鏈接對象conn
SqlConnection conn = new SqlConnection(connStr); //SqlConnection 變量名 = new SqlConnection(參數(shù)字符串或存儲了參數(shù)字符串的變量);
進行鏈接的測試,運行不報錯即鏈接成功
conn.Open();//打開數(shù)據(jù)庫鏈接,越晚開越好 conn.Close();//關(guān)閉數(shù)據(jù)庫鏈接,用完就關(guān),別掛著
必要準(zhǔn)備已經(jīng)OK了
下面來講sql語句的編寫和執(zhí)行。
SQL語句編寫加執(zhí)行
編寫
我們定義一個string類型的sql變量來存儲我們的sql語句,sql語句只需用原本的語法即可,無需做變化。
sqlserver中創(chuàng)建數(shù)據(jù)表一般是這么寫的
這里把他轉(zhuǎn)成一行的,不用管縮進 。
string sql = "create table csdn予我心安的數(shù)據(jù)表1(name varchar(8) not null)";
有人會問,我的sql語句內(nèi)容要持續(xù)變化,但格式基本不變咋辦。總不能另寫一條吧。其實沒那么折騰,用C#的String.Format()生成sql語句字符串就好了.
比如說我要創(chuàng)建的數(shù)據(jù)表名要替換,我們在表名這加個占位符就OK
string tablename="csdn予我心安的數(shù)據(jù)表1";//我是表名 string sql = String.Format("create table {0}(name varchar(8) not null)", tablename); //tablename的內(nèi)容會替換掉字符串中的{0},所以sql的內(nèi)容會隨著tablename變換而改變
執(zhí)行
創(chuàng)建執(zhí)行器
sql語句我們已經(jīng)寫好了,接下了就要執(zhí)行了
我們調(diào)用SqlCommand類生成一個sql語句執(zhí)行器cmd,傳入sql語句和鏈接變量
SqlCommand cmd = new SqlCommand(sql, conn); //格式: SqlCommand 自定義執(zhí)行器變量名= new SqlCommand(sql字符串變量, 鏈接變量);
執(zhí)行器我們創(chuàng)建好了,接下來要選擇執(zhí)行方法,不同的執(zhí)行方法有不同的返回值。
特別提醒:使用前記得打開鏈接
conn.Open();
ExecuteNonQuery()方式執(zhí)行
cmd.ExecuteNonQuery();
ExecuteScalar()方式執(zhí)行
cmd.ExecuteScalar();
二者區(qū)別
ExecuteReader()方式執(zhí)行
cmd.ExecuteReader();
這個執(zhí)行方式的作用我會在下面的實例中詳細講解
特別提醒:執(zhí)行完請關(guān)閉連接
conn.Close();
實例:
1-創(chuàng)建一張數(shù)據(jù)表
為小明創(chuàng)建一張個人成績表
要用到sql語句中創(chuàng)建數(shù)據(jù)表的指令
create table 表名 ( 列名 數(shù)據(jù)類型 是否允許為空(null||not null), 列名2 數(shù)據(jù)類型 是否允許為空(null||not null), 列名3 數(shù)據(jù)類型 是否允許為空(null||not null), …… 列名n 數(shù)據(jù)類型 是否允許為空(null||not null) )
C#代碼
using System.Data.SqlClient;//頭別忘了,如果加了頭還顯示未調(diào)用,請檢查Nuget包 public static void addtable(string tablename) { //測試連接數(shù)據(jù)庫 string connStr = "Data Source=LAPTOP-82MUPKTO;Initial Catalog=CSDN予我心安A3的數(shù)據(jù)庫;Integrated Security=True"; SqlConnection conn = new SqlConnection(connStr); //打開數(shù)據(jù)庫 conn.Open(); //編寫sql語句,語法即sql語法 string sql = String.Format("create table {0}(課程名 varchar(11) not null,成績 tinyint not null)", tablename); SqlCommand cmd = new SqlCommand(sql, conn); //貼心,異常處理都安排上了 try { cmd.ExecuteNonQuery(); Console.WriteLine("數(shù)據(jù)表創(chuàng)建成功"); } catch (SqlException ae) { Console.WriteLine("數(shù)據(jù)表創(chuàng)建失敗"); Console.WriteLine(ae.Message); } finally { conn.Close();//對數(shù)據(jù)庫操作完成后,需要關(guān)閉數(shù)據(jù)庫,釋放內(nèi)存 } } addtable("考試成績表")
蕪湖起飛
2-向表中插入數(shù)據(jù)
小明的計算機科學(xué)考試考了100分,幫他錄進去
要用到sql中的插入數(shù)據(jù)指令
insert into 表名 values ('數(shù)據(jù)1','數(shù)據(jù)2','數(shù)據(jù)3')//第一行數(shù)據(jù),表結(jié)構(gòu)有幾列就幾個唄,允許為空的地方可以就打'' ('數(shù)據(jù)1','數(shù)據(jù)2','數(shù)據(jù)3')//第二行數(shù)據(jù),表結(jié)構(gòu)有幾列就幾個唄,允許為空的地方可以就打''
public static void adddata(string classname,int grade) { //測試連接數(shù)據(jù)庫 string connStr = "Data Source=LAPTOP-82MUPKTO;Initial Catalog=CSDN予我心安A3的數(shù)據(jù)庫;Integrated Security=True"; SqlConnection conn = new SqlConnection(connStr); //打開數(shù)據(jù)庫 conn.Open(); //編寫sql語句,語法即sql語法 string sql = String.Format("insert into 考試成績表 values('{0}','{1}')",classname,grade); SqlCommand cmd = new SqlCommand(sql, conn); try { cmd.ExecuteNonQuery(); Console.WriteLine("成績錄入成功"); } catch (SqlException ae) { Console.WriteLine("成績錄入失敗"); Console.WriteLine(ae.Message); } finally { conn.Close();//對數(shù)據(jù)庫操作完成后,需要關(guān)閉數(shù)據(jù)庫,釋放內(nèi)存 } } data_Control.adddata("計算機科學(xué)",100);
3-修改表中數(shù)據(jù)
我去,小明考試作弊被發(fā)現(xiàn),成績0分,幫他改過來
update 表名 set 列名1='值',列名2='值' where 篩選條件
public static void changedata(string classname,int new_grade) { //測試連接數(shù)據(jù)庫 string connStr = "Data Source=LAPTOP-82MUPKTO;Initial Catalog=CSDN予我心安A3的數(shù)據(jù)庫;Integrated Security=True"; SqlConnection conn = new SqlConnection(connStr); //打開數(shù)據(jù)庫 conn.Open(); //編寫sql語句,語法即sql語法 string sql = String.Format("update 考試成績表 set 成績='{0}' where 課程名='{1}'", new_grade,classname); SqlCommand cmd = new SqlCommand(sql, conn); try { cmd.ExecuteNonQuery(); Console.WriteLine("成績修改成功"); } catch (SqlException ae) { Console.WriteLine("成績修改失敗"); Console.WriteLine(ae.Message); } finally { conn.Close();//對數(shù)據(jù)庫操作完成后,需要關(guān)閉數(shù)據(jù)庫,釋放內(nèi)存 } } changedata("計算機科學(xué)",0);
4-刪除表中數(shù)據(jù)
小明害怕被老爸竹筍炒肉絲,給我1包辣條賄賂我刪掉這條記錄,我肯定不會為了一包辣條就幫他
,但他拿了2包就是另一回事了。
delete from 表名 where 篩選條件
public static void delete_data(string classname) { //測試連接數(shù)據(jù)庫 string connStr = "Data Source=LAPTOP-82MUPKTO;Initial Catalog=CSDN予我心安A3的數(shù)據(jù)庫;Integrated Security=True"; SqlConnection conn = new SqlConnection(connStr); //打開數(shù)據(jù)庫 conn.Open(); //編寫sql語句,語法即sql語法 string sql = String.Format("delete from 考試成績表 where 課程名='{0}'", classname); SqlCommand cmd = new SqlCommand(sql, conn); try { cmd.ExecuteNonQuery(); Console.WriteLine("成績刪除成功"); } catch (SqlException ae) { Console.WriteLine("成績刪除失敗"); Console.WriteLine(ae.Message); } finally { conn.Close();//對數(shù)據(jù)庫操作完成后,需要關(guān)閉數(shù)據(jù)庫,釋放內(nèi)存 } } delete_data("計算機科學(xué)");
小明開心的回家了,他一走我又把成績寫回去了……
5-讀取表中數(shù)據(jù)
學(xué)校要把小明的成績單打印出來。
ExecuteReader()的用法來了啊,謝謝你看到這里。
用法就在下面的代碼中啦
select * from 考試成績表
public static void get_data() { //測試連接數(shù)據(jù)庫 string connStr = "Data Source=LAPTOP-82MUPKTO;Initial Catalog=CSDN予我心安A3的數(shù)據(jù)庫;Integrated Security=True"; SqlConnection conn = new SqlConnection(connStr); //打開數(shù)據(jù)庫 conn.Open(); //編寫sql語句,語法即sql語法 string sql = String.Format("select * from 考試成績表"); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataReader rdr = cmd.ExecuteReader();//定義數(shù)據(jù)讀取器rdr獲取傳回的數(shù)據(jù) while (rdr.Read())//每次執(zhí)行一次Read(),從數(shù)據(jù)里讀取一行數(shù)據(jù) { string classname=rdr["課程名"].ToString();//根據(jù)列名,獲得該行里的課程名信息,由于rdr["課程名"]返回的是object類型,所以要進行類型轉(zhuǎn)化,下面成績一樣的原理 int grade = Convert.ToInt32(rdr["成績"]);//根據(jù)列名,獲得該行里的成績信息 Console.WriteLine("課程名:{0},成績:{1}",classname,grade); } conn.Close();//讀取時要一直保證數(shù)據(jù)庫是打開的 }
小明傷心的拿著成績單走了..........
總結(jié)
到此這篇關(guān)于如何利用C#通過sql語句操作Sqlserver數(shù)據(jù)庫教程的文章就介紹到這了,更多相關(guān)C# sql語句操作Sqlserver數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!