C# 數據庫SQl語句

1。空置處理
ISNULL
2、分組
group by
select
Classid as 班級id,
班級人數=Count(*)
from TblStudent
group by ClassID
當時用了分組語句(group by)或者是聚合函數的時候,在select的查詢列表中不能包含其他列名除非這列也包含在分組語句中,或者寫一個聚合函數(Count)


使用having 對分組以後的數據進行篩選
having 與where都是對數據進行篩選,where對分組前的每行數據篩選,having對分組後的每行數據篩選

select
Classid as 班級id,
班級人數=Count(*)
from TblStudent
group by ClassID
having Count(*)>1
order by 班級人數 asc

語句執行順序
from 表
where 條件
Group by 列
Having篩選條件
Order by 列


3、類型轉換函數
select 100+200
select 100+'1000'
print 'a'+100 不行哦


cast()
convert()
select 100.0+cast('1000' as int )
OK
select 100.0+convert(int,'1000')

4、union 聯合結果集(集合運算符)
把多個結果集中的行聯合起來
union 和union all 都能進行聯合
區別: union會去除重複,重新排列數據
union all 不會去除重複也不重新排列

大多數情況下聯合的時候不需要保持數據的順序,所以一般建議使用union all



使用union向表中插入多條數據
insert into Tblstudent
select XXXXX
union all
select XXXXX
union all
select XXXXX
union all
select XXXXX
union all

5、向表中插入多條記錄
select * from Tble11 from Tblstudent
新表中沒有以前表的約束

6、字符串函數
1、len()計算字符的個數
print len(‘Hi-最近好嗎? ’)
datalength()返回所佔用字節的個數,這個不是字符串函數
2、upper 轉換大寫 lower()轉換小寫
3、去掉兩端空格ltrim rtrim
4、字符串截取函數
left()
right()
substring()截取字符串
substring(XXXXX,1,3)
從幾開始,截取幾個。



7、日期函數
getdate()
sysdatetime()

dateadd(day,200,getdate())

DATEDIFF ( datepart , startdate , enddate )計算兩個日期的差

獲取日期的某部分值
year(getdate())
month(getdate())
datepart(datepart,getdate())

8、ADO.NET
Connection 連接數據庫
Command 執行SQL語句
DataReader 只讀、只進的結果集,一條條讀取數據。
DataAdapter 封裝了上面的三個對象
DataSet 臨時數據庫


//連接數據庫步驟
//1.創建連接字符串
//Data Source=ASUS;
//Initial Catalog=Honest;
//Integrated Security=True
string constr = "Data Source=ASUS;INITIAL Catalog=study; Integrated Security=True";
//2.創建連接對象
//相當於TRY Finaly
using (SqlConnection con = new SqlConnection(constr))
{
//測試,打開連接
//3。打開連接
con.Open();
Console.WriteLine("打開成功");
//4.關閉連接,釋放資源

}
Console.WriteLine("關閉連接,釋放資源!!!");
Console.ReadKey();

DataReader特點:
1、只讀、 只進(不能後退).只能通過reader讀取數據,不能修改。reader只能一條條向前移動,不能後退
2、使用reader時必須保證連接是打開狀態。reader使用完畢後必須關閉,釋放。同時關閉釋放連接對象
3、reader默認情況下要求獨佔一個連接對象。


網數據庫插入值返回自動編號:
insert into Tbclass output inserted.tClassId valus('dsadsa','dsadas')



9.防止SQL注入:
使用帶參數的SQL語句或者存儲過程。
string sql = string.Format("SELECT COUNT(*) FROM dbo.[User] WHERE u_id=@user AND u_pwd=@password");









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章