C# 操作Sql Server 学习总结
生活随笔
收集整理的這篇文章主要介紹了
C# 操作Sql Server 学习总结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C#中產生SQL語句的幾種方式
(1)拼接產生SQL語句:
? ? ? ?string sql = "insert into czyb(yhm,mm,qx) values('" + txtName.Text + "','" + txtPassword.Text + "','" + cmbPriority.Text + "')";
? ? ? ?OleDbCommand cmd = new OleDbCommand(sql, conn);
? ? ? ?這種方法寫法比較復雜,且安全性低,容易遭受SQL注入攻擊。
(2)用string.Format方法:
? ? ? string sql = string.Format("insert into czyb(yhm,mm,qx) values('{0}','{1}','{2}')", txtName.Text, txtPassword.Text, cmbPriority.Text);
? ? ? 只是可讀性優于第(1)種。
(3)用參數化SQL語句:
? ? ? string sql="insert into czyb(yhm,mm,qx) values (@yhm,@mm,@qx)";
? ? ? OleDbCommand cmd = new OleDbCommand();
? ? ? cmd.CommandText = sql;
? ? ? cmd.Parameters.AddWithValue("@yhm", txtName.Text);
? ? ? cmd.Parameters.AddWithValue("@mm", txtPassword.Text);
? ? ? cmd.Parameters.AddWithValue("@qx", cmbPriority.Text);
? ? ? cmd.Connection = conn;
? ? ? conn.Open();
? ? ? cmd.ExecuteNonQuery();
? ? ?代碼結構清楚,對于不支持存儲過程的數據庫(如Access),推薦采用本方法。
(4)如果數據庫支持存儲過程(如SQL Server),可以調用存儲過程執行SQL:
? ? ? ? SqlConnection conn = new SqlConnection(txtConn);
? ? ? ? SqlCommand cmd = new SqlCommand("SearchContact", conn); ?//存儲過程名稱為SearchContact
? ? ? ? cmd.CommandType = CommandType.StoredProcedure;
? ? ? ? cmd.Parameters.Add("@name", SqlDbType.VarChar, 50); ? //傳入參數
? ? ? ? cmd.Parameters["@name"].Value = txtName.Text.Trim();
? ? ? ?由于存儲過程是數據庫預編譯的,執行效率高,推薦采用。
========
C#連接SQL Server數據庫代碼解析
連接字符串:
<connectionStrings>
<add name="conn" connectionString="user id=sa;Password=;initial catalog=Northwind;Server=YourSQLServer;Connect Timeout=30;" providerName="System.Data.SqlClient" />
</connectionStrings>
--------------------------------------------------------------------------------
參數介紹(注意:參數間用分號分隔):
"user id=sa":連接數據庫的驗證用戶名為sa.他還有一個別名"uid",所以這句我們還可以寫成"uid=sa".
"password=":連接數據庫的驗證密碼為空.他的別名為"pwd",所以我們可以寫為"pwd=".
這里注意,你的SQL Server必須已經設置了需要用戶名和密碼來登錄,否則不能用這樣的方式來登錄.如果你的SQL Server設置為Windows登錄,那么在這里就不需要使用"user id"和"password"這樣的方式來登錄,而需要使用"Trusted_Connection=SSPI"來進行登錄.
"initial catalog=Northwind":使用的數據源為"Northwind"這個數據庫.他的別名為"Database",本句可以寫成"Database=Northwind".
"Server=YourSQLServer":使用名為"YourSQLServer"的服務器.他的別名為"Data Source","Address","Addr".如果使用的是本地數據庫且定義了實例名,則可以寫為"Server=(local)\實例名";如果是遠程服務器,則將"(local)"替換為遠程服務器的名稱或IP地址.
"Connect Timeout=30":連接超時時間為30秒.
注:以上User ID,Password可以大寫也可以小寫,與大小寫無關
========
用c#讀取并分析sql2005日志
??用過logExplorer的朋友都會被他強悍的功能吸引,我寫過一篇詳細的操作文檔可以參考
http://blog.csdn.net/jinjazz/archive/2008/05/19/2459692.aspx
我們可以自己用開發工具來實現sql日志的讀取,這個應用還是很酷的,具體思路
1、首先要了解一個沒有公開的系統函數::fn_dblog,他可以讀取sql日志,并返回二進制的行數據
2、然后要了解sql的二進制數據是如何存儲的,這個可以參考我的blog文章
http://blog.csdn.net/jinjazz/archive/2008/08/07/2783872.aspx
3、用自己擅長的開發工具來分析數據,得到我們需要的信息
我用c#寫了一個測試樣例,分析了int,char,datetime和varchar的日志情況而且沒有考慮null和空字符串的保存,希望感興趣的朋友能和我一起交流打造屬于自己的日志分析工具
詳細的試驗步驟以及代碼如下:
1、首先建立sqlserver的測試環境,我用的sql2005,這個過程不能保證在之前的版本中運行
以下sql語句會建立一個dbLogTest數據庫,并建立一張log_test表,然后插入3條數據之后把表清空
use master
go
create database dbLogTest
go
use ?dbLogTest
go
create table log_test(id int ,code char(10),name varchar(20),date datetime,memo varchar(100))
insert into log_test select 100, 'id001','jinjazz',getdate(),'剪刀'
insert into log_test select 65549,'id002','游客',getdate()-1,'這家伙很懶,沒有設置昵稱'
insert into log_test select -999,'id003','這家伙來自火星',getdate()-1000,'a'
delete from log_test
--use master?
--go
--drop database dbLogTest
2、我們最終的目的是要找到被我們刪掉的數據
3、分析日志的c#代碼:我已經盡量詳細的寫了注釋
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication21
{
? ? class Program
? ? {
? ? ? ? /// <summary>
? ? ? ? /// 分析sql2005日志,找回被delete的數據,引用請保留以下信息
? ? ? ? /// 作者:jinjazz (csdn的剪刀)
? ? ? ? /// 作者blog:http://blog.csdn.net/jinjazz
? ? ? ? /// </summary>
? ? ? ? /// <param name="args"></param>
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection())
? ? ? ? ? ? {
? ? ? ? ? ? ? ? conn.ConnectionString = "server=localhost;uid=sa;pwd=sqlgis;database=dbLogTest";
? ? ? ? ? ? ? ? conn.Open();
? ? ? ? ? ? ? ? using (System.Data.SqlClient.SqlCommand command = conn.CreateCommand())
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? //察看dbo.log_test對象的sql日志
? ? ? ? ? ? ? ? ? ? command.CommandText = @"SELECT allocunitname,operation,[RowLog Contents 0] as r0,[RowLog Contents 1]as r1?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? from::fn_dblog (null, null) ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? where allocunitname like 'dbo.log_test%'and
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? operation in('LOP_INSERT_ROWS','LOP_DELETE_ROWS')";
? ? ? ? ? ? ? ? ? ? System.Data.SqlClient.SqlDataReader reader = command.ExecuteReader();
? ? ? ? ? ? ? ? ? ? //根據表字段的順序建立字段數組
? ? ? ? ? ? ? ? ? ? Datacolumn[] columns = new Datacolumn[]
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? new Datacolumn("id", System.Data.SqlDbType.Int),
? ? ? ? ? ? ? ? ? ? ? ? ? ? new Datacolumn("code", System.Data.SqlDbType.Char,10),
? ? ? ? ? ? ? ? ? ? ? ? ? ? new Datacolumn("name", System.Data.SqlDbType.VarChar),
? ? ? ? ? ? ? ? ? ? ? ? ? ? new Datacolumn("date", System.Data.SqlDbType.DateTime),
? ? ? ? ? ? ? ? ? ? ? ? ? ? new Datacolumn("memo", System.Data.SqlDbType.VarChar)
? ? ? ? ? ? ? ? ? ? ? ? };
? ? ? ? ? ? ? ? ? ? //循環讀取日志
? ? ? ? ? ? ? ? ? ? while (reader.Read())
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? byte[] data = (byte[])reader["r0"];
? ? ? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? ? ? ? ? try
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? //把二進制數據結構轉換為明文
? ? ? ? ? ? ? ? ? ? ? ? ? ? TranslateData(data, columns);
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("數據對象{1}的{0}操作:", reader["operation"], reader["allocunitname"]);
? ? ? ? ? ? ? ? ? ? ? ? ? ? foreach (Datacolumn c in columns)
? ? ? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("{0} = {1}", c.Name, c.Value);
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine();
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? catch
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? //to-do...
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? reader.Close();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? conn.Close();
? ? ? ? ? ? }
? ? ? ? ? ? Console.WriteLine("************************日志分析完成");
? ? ? ? ? ? Console.ReadLine();
? ? ? ? }
? ? ? ? //自定義的column結構
? ? ? ? public class Datacolumn
? ? ? ? {
? ? ? ? ? ? public string Name;
? ? ? ? ? ? public System.Data.SqlDbType DataType;
? ? ? ? ? ? public short Length = -1;
? ? ? ? ? ? public object Value = null;
? ? ? ? ? ? public Datacolumn(string name, System.Data.SqlDbType type)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Name = name;
? ? ? ? ? ? ? ? DataType = type;
? ? ? ? ? ? }
? ? ? ? ? ? public Datacolumn(string name,System.Data.SqlDbType type,short length)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Name = name;
? ? ? ? ? ? ? ? DataType = type;
? ? ? ? ? ? ? ? Length = length;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? /// <summary>
? ? ? ? /// sql二進制結構翻譯,這個比較關鍵,測試環境為sql2005,其他版本沒有測過。
? ? ? ? /// </summary>
? ? ? ? /// <param name="data"></param>
? ? ? ? /// <param name="columns"></param>
? ? ? ? static void TranslateData(byte[] data, Datacolumn[] columns)
? ? ? ? {
? ? ? ? ? ? //我只根據示例寫了Char,DateTime,Int三種定長度字段和varchar一種不定長字段,其余的有興趣可以自己補充
? ? ? ? ? ? //這里沒有暫時沒有考慮Null和空字符串兩種情況,以后會補充。
? ? ? ? ? ? //引用請保留以下信息:
? ? ? ? ? ? //作者:jinjazz?
? ? ? ? ? ? //sql的數據行二進制結構參考我的blog
? ? ? ? ? ? //http://blog.csdn.net/jinjazz/archive/2008/08/07/2783872.aspx
? ? ? ? ? ? //行數據從第5個字節開始
? ? ? ? ? ? short index = 4;
? ? ? ? ? ? //先取定長字段
? ? ? ? ? ? foreach (Datacolumn c in columns)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? switch (c.DataType)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? case System.Data.SqlDbType.Char:
? ? ? ? ? ? ? ? ? ? ? ? //讀取定長字符串,需要根據表結構指定長度
? ? ? ? ? ? ? ? ? ? ? ? c.Value = System.Text.Encoding.Default.GetString(data,index,c.Length);
? ? ? ? ? ? ? ? ? ? ? ? index += c.Length;
? ? ? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? ? ? case System.Data.SqlDbType.DateTime:
? ? ? ? ? ? ? ? ? ? ? ? //讀取datetime字段,sql為8字節保存
? ? ? ? ? ? ? ? ? ? ? ? System.DateTime date = new DateTime(1900, 1, 1);
? ? ? ? ? ? ? ? ? ? ? ? //前四位1/300秒保存
? ? ? ? ? ? ? ? ? ? ? ? int second = BitConverter.ToInt32(data, index);
? ? ? ? ? ? ? ? ? ? ? ? date = date.AddSeconds(second/300);
? ? ? ? ? ? ? ? ? ? ? ? index += 4;
? ? ? ? ? ? ? ? ? ? ? ? //后四位1900-1-1的天數
? ? ? ? ? ? ? ? ? ? ? ? int days = BitConverter.ToInt32(data, index);
? ? ? ? ? ? ? ? ? ? ? ? date=date.AddDays(days);
? ? ? ? ? ? ? ? ? ? ? ? index += 4;
? ? ? ? ? ? ? ? ? ? ? ? c.Value = date;
? ? ? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? ? ? case System.Data.SqlDbType.Int:
? ? ? ? ? ? ? ? ? ? ? ? //讀取int字段,為4個字節保存
? ? ? ? ? ? ? ? ? ? ? ? c.Value = BitConverter.ToInt32(data, index);
? ? ? ? ? ? ? ? ? ? ? ? index += 4;
? ? ? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? ? ?default:
? ? ? ? ? ? ? ? ? ? ? ?//忽略不定長字段和其他不支持以及不愿意考慮的字段
? ? ? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? //跳過三個字節
? ? ? ? ? ? index += 3;
? ? ? ? ? ? //取變長字段的數量,保存兩個字節
? ? ? ? ? ? short varColumnCount = BitConverter.ToInt16(data, index);
? ? ? ? ? ? index += 2;
? ? ? ? ? ? //接下來,每兩個字節保存一個變長字段的結束位置,
? ? ? ? ? ? //所以第一個變長字段的開始位置可以算出來
? ? ? ? ? ? short startIndex =(short)( index + varColumnCount * 2);
? ? ? ? ? ? //第一個變長字段的結束位置也可以算出來
? ? ? ? ? ? short endIndex = BitConverter.ToInt16(data, index);
? ? ? ? ? ? //循環變長字段列表讀取數據
? ? ? ? ? ? foreach (Datacolumn c in columns)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? switch (c.DataType)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? case System.Data.SqlDbType.VarChar:
? ? ? ? ? ? ? ? ? ? ? ? //根據開始和結束位置,可以算出來每個變長字段的值
? ? ? ? ? ? ? ? ? ? ? ? c.Value =System.Text.Encoding.Default.GetString(data, startIndex, endIndex - startIndex);
? ? ? ? ? ? ? ? ? ? ? ? //下一個變長字段的開始位置
? ? ? ? ? ? ? ? ? ? ? ? startIndex = endIndex;
? ? ? ? ? ? ? ? ? ? ? ? //獲取下一個變長字段的結束位置
? ? ? ? ? ? ? ? ? ? ? ? index += 2;
? ? ? ? ? ? ? ? ? ? ? ? endIndex = BitConverter.ToInt16(data, index);
? ? ? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? ? ? default:
? ? ? ? ? ? ? ? ? ? ? ? //忽略定長字段和其他不支持以及不愿意考慮的字段
? ? ? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? //獲取完畢
? ? ? ? }
? ? }
}
4、更改你的sql連接字符串后運行以上代碼,會看到如下輸出信息:
數據對象dbo.log_test的LOP_INSERT_ROWS操作:
id = 100
code = id001
name = jinjazz
date = 2008-8-7 18:14:03
memo = 剪刀
數據對象dbo.log_test的LOP_INSERT_ROWS操作:
id = 65549
code = id002
name = 游客
date = 2008-8-6 18:14:03
memo = 這家伙很懶,沒有設置昵稱
數據對象dbo.log_test的LOP_INSERT_ROWS操作:
id = -999
code = id003
name = 這家伙來自火星
date = 2005-11-11 18:14:03
memo = a
數據對象dbo.log_test的LOP_DELETE_ROWS操作:
id = 100
code = id001
name = jinjazz
date = 2008-8-7 18:14:03
memo = 剪刀
數據對象dbo.log_test的LOP_DELETE_ROWS操作:
id = 65549
code = id002
name = 游客
date = 2008-8-6 18:14:03
memo = 這家伙很懶,沒有設置昵稱
數據對象dbo.log_test的LOP_DELETE_ROWS操作:
id = -999
code = id003
name = 這家伙來自火星
date = 2005-11-11 18:14:03
memo = a
************************日志分析完成
試驗成功~~
dbcc log和fn_dblog函數真的是分析日志文件嗎??
這個問題需要了解CheckPoint和sql的存儲機制,首先參考如下文檔?
http://msdn.microsoft.com/zh-cn/library/ms188748.aspx?
CheckPoint?
將當前數據庫的全部臟頁寫入磁盤。“臟頁”是已輸入緩存區高速緩存且已修改但尚未寫入磁盤的數據頁。CHECKPOINT 可創建一個檢查點,在該點保證全部臟頁都已寫入磁盤,從而在以后的恢復過程中節省時間。?
什么時候執行它?大致有幾種情況:?
手動調用、sql自動定時執行、數據庫脫機之類操作、數據庫進程正常終止等情況。?
簡單日志模型的原理就是每次checkpoint后自動截斷日志。?
dbcc log到底有什么用?和checkpoint有什么關系?
在事物外執行過CheckPoint后,dbcc log語句將無法獲取之前的日志。所以我推斷此語句是系統為了在非正常關閉數據庫的狀態下,來保證日志,內存中的臟頁和數據文件的一致性的措施,此方法并不是讀取日志文件的全部信息。?
log explorer的原理?
還沒有搞清楚,此前的推斷是錯誤的,它不是通過dbcc log 或者fn_dblog方法實現的,不但CheckPoint對它沒有影響,而且他會主動調用這個語句。
日志分析工具宣告流產,不過基本上搞清了日志和數據文件的存儲結構,希望以后仍然可以用的上這些經驗
========
解析c#得到局域網內所有sqlserver數據庫實例
官方的做法是這樣的:
using System.Data.Sql; ?
?
class Program ?
{ ?
? static void Main() ?
? { ?
? ? // Retrieve the enumerator instance and then the data. ?
? ? SqlDataSourceEnumerator instance = ?
? ? ? SqlDataSourceEnumerator.Instance; ?
? ? System.Data.DataTable table = instance.GetDataSources(); ?
?
? ? // Display the contents of the table. ?
? ? DisplayData(table); ?
?
? ? Console.WriteLine("Press any key to continue."); ?
? ? Console.ReadKey(); ?
? } ?
?
? private static void DisplayData(System.Data.DataTable table) ?
? { ?
? ? foreach (System.Data.DataRow row in table.Rows) ?
? ? { ?
? ? ? foreach (System.Data.DataColumn col in table.Columns) ?
? ? ? { ?
? ? ? ? Console.WriteLine("{0} = {1}", col.ColumnName, row[col]); ?
? ? ? } ?
? ? ? Console.WriteLine("============================"); ?
? ? } ?
? } ?
}?
來源于:http://msdn.microsoft.com/en-us/library/system.data.sql.sqldatasourceenumerator.getdatasources.aspx
請看遇到的問題及解決方法:
?
實際上問題就是,得到的結果只有服務器名字,但由于是默認實例,所以并沒有實例名字。而且,假如安裝的是sqlserver,則連接數據庫是必須是 服務器\sqlexpress(默認實例名稱);假如安裝的是完整版的sqlexpress,則只需 服務器 即可連接。這就造成了不少問題。 上邊百度給出比較好的解決方法。
?
本文出自 “獨釣寒江雪” 博客,請務必保留此出處http://zhaojie.blog.51cto.com/1768828/932275
========
C#數據庫查詢和操作大全
一:C#數據庫查詢之數據庫連接代碼:SqlConnectionobjSqlConnection=newSqlConnection("server=127.0.0.1;uid=sa;pwd=;database=test"); ?
objSqlConnection.Open();?
二:數據庫的添加記錄代碼:
inti=0; ?
strings1="",s2=""; ?
i=Convert.ToInt16(textBox1.Text); ?
s1=textBox2.Text; ?
s2=textBox3.Text; ?
?
SqlConnectionobjSqlConnection=newSqlConnection("server=127.0.0.1;uid=sa;pwd=;database=test"); ?
objSqlConnection.Open(); ?
?
MessageBox.Show("數據庫連接成功","好"); ?
?
try ?
{ ?
SqlCommandsqlcom=newSqlCommand("insertintoinfo(id,name,sex)values("+i+",'"+s1+"','"+s2+"')",objSqlConnection); ?
sqlcom.ExecuteNonQuery(); ?
MessageBox.Show("添加成功!","啊"); ?
} ?
catch(Exceptiona) ?
{ ?
MessageBox.Show(a.ToString()); ?
} ?
MessageBox.Show("添加成功!","啊"); ?
}?
三:數據庫的修改代碼:
inti=0; ?
strings1="",s2=""; ?
s1=textBox2.Text; ?
s2=textBox3.Text; ?
if(textBox1.Text.Length==0) ?
i=0; ?
else?
i=Convert.ToInt32(textBox1.Text); ?
?
SqlConnectionobjSqlConnection=newSqlConnection("server=127.0.0.1;uid=sa;pwd=;database=test"); ?
objSqlConnection.Open(); ?
MessageBox.Show("數據庫連接成功","好"); ?
try ?
{ ?
SqlCommandsqlcom=newSqlCommand("updateinfosetname='"+s1+"',sex='"+s2+"'"+"whereid="+i,objSqlConnection); ?
sqlcom.ExecuteNonQuery(); ?
MessageBox.Show("修改成功!","啊"); ?
objSqlConnection.Close(); ?
} ?
catch(Exceptiona) ?
{ ?
MessageBox.Show(a.ToString()); ?
}?
四:數據庫的刪除代碼:
inti=0; ?
strings1="",s2=""; ?
s1=textBox2.Text; ?
s2=textBox3.Text; ?
if(textBox1.Text.Length==0) ?
i=0; ?
else?
i=Convert.ToInt16(textBox1.Text); ?
SqlConnectionobjSqlConnection=newSqlConnection("server=127.0.0.1;uid=sa;pwd=;database=test"); ?
objSqlConnection.Open(); ?
MessageBox.Show("數據庫連接成功","好"); ?
try?
{ ?
SqlCommandsqlcom=newSqlCommand("deletefrominfowhereid="+i,objSqlConnection); ?
?
sqlcom.ExecuteNonQuery(); ?
?
MessageBox.Show("刪除成功!","啊"); ?
?
objSqlConnection.Close(); ?
} ?
catch(Exceptiona) ?
{ ?
MessageBox.Show(a.ToString()); ?
}?
五:數據庫的查詢代碼:
1.類開始:
DataTabledt1=newDataTable(); ?
SqlDataAdapterda1=newSqlDataAdapter();?
2.按鈕代碼:
inti=0,n=0; ?
strings1="",s2=""; ?
s1=textBox2.Text; ?
s2=textBox3.Text; ?
if(textBox1.Text.Length==0) ?
i=0; ?
else?
i=Convert.ToInt32(textBox1.Text); ?
SqlConnectionobjSqlConnection=newSqlConnection("server=127.0.0.1;uid=sa;pwd=;database=test"); ?
objSqlConnection.Open(); ?
MessageBox.Show("數據庫連接成功","好"); ?
?
stringquery="SELECT*frominfowhereid="+i; ?
?
DataSetobjDataSet=newDataSet(); ?
?
SqlDataAdapterobj=newSqlDataAdapter(); ?
?
obj.SelectCommand=newSqlCommand(query,objSqlConnection); ?
?
obj.Fill(objDataSet,"info"); ?
?
SqlCommandobjSqlCommand=newSqlCommand(query,objSqlConnection); ?
?
SqlDataReaderobjSqlReader=objSqlCommand.ExecuteReader(); ?
?
while(objSqlReader.Read()) ?
{ ?
n+=1; ?
MessageBox.Show("編號:"+objSqlReader.Getvalue(0)+"姓名:"+objSqlReader.Getvalue(1)+"性別"+objSqlReader.Getvalue(2)); ?
} ?
if(n==0) ?
MessageBox.Show("數據庫中沒有這樣的記錄!");?
六:C#數據庫查詢代碼:
inti=0; ?
//intn=0; ?
strings1="",s2=""; ?
stringsql; ?
s1=textBox2.Text; ?
s2=textBox3.Text; ?
?
if(textBox1.Text.Length==0) ?
{ ?
i=0; ??
} ?
else?
i=Convert.ToInt32(textBox1.Text); ?
SqlConnectionobjSqlConnection=newSqlConnection("server=127.0.0.1;uid=sa;pwd=;database=test"); ?
objSqlConnection.Open(); ?
MessageBox.Show("數據庫連接成功","好"); ?
stringquery="SELECT*frominfowhereid="+i; ?
if(i==0) ?
sql="select*frominfo"; ?
else?
sql="select*frominfowhereid="+i; ?
da1=newSqlDataAdapter(sql,objSqlConnection); ?
dt1.Clear(); ?
da1.Fill(dt1); ?
dataGridView1.DataSource=dt1;?
C#數據庫查詢之數據庫的封裝類代碼:
classDBClass ?
{ ??
publicvoiddbclass(stringsql) ?
{ ?
try?
{ ?
SqlConnectionsqlcon=newSqlConnection("server=127.0.0.1;uid=sa;pwd=;database=test"); ?
sqlcon.Open(); ?
?
SqlTransactionobjt=sqlcon.BeginTransaction();//事物開始 ?
?SqlCommandsqlcom=newSqlCommand(sql,sqlcon); ?
?sqlcom.Transaction=objt;//將Command對象設置為事物處理的對象 ?
?sqlcom.ExecuteNonQuery(); ?
objt.Commit();//提交事物 ?
sqlcon.Close(); ?
} ?
catch(Exceptiona) ?
{ ?
MessageBox.Show(a.ToString()); ?
} ?
} ?
} ?
--db2數據庫連接代碼: ?
stringstrcon="Provider=IBMDADB2;DataSource=hfzd;UserId=db2admin;Password=db2admin"; ?
//stringsql="select*fromADMINISTRATOR.HFZD"; ?
stringsql="deletefromADMINISTRATOR.HFZDwhereID=1"; ?
OleDbConnectionolecon=newOleDbConnection(strcon); ?
olecon.Open(); ?
MessageBox.Show("數據庫已連接上"); ?
dt.Clear(); ?
da=newOleDbDataAdapter(sql,olecon); ?
da.Fill(dt); ?
dataGridView1.DataSource=dt; ?
olecon.Close();
========
C#與SQL常用操作
ADO.NET中對數據庫的操作是:斷開式連接,只需要寫一次連接服務器,庫名,用戶名,密碼的字符串,以后只對con 進行close()和con.Open() 操作即可連接數據庫
? ? ? ?先從數據庫中取出結果集后進行處理數據后再UpData更新到數據庫(共三步)
? ? ? ?如果只想讀取和顯示數據 則只需使用數據讀取器 SqlDataReader即可, 但要處理數據然后更新數據庫(增加,更改),就需要用數據集DataSet和
? ? ? ?數據適配器SqlDataAdaper
?
SqlDataAdapter在下面有用法:
?
其中:讀取數據時用SqlDataReader是固定的 但是處理數據更新時(增加,更改)為兩種情況,(一)直接拼SQL語句 適用于簡單的表,
? ? ? ?(二)用參數的 用到SqlDataAdaper 適用于復雜的表
? ? ? 建議:簡單的表可以用(一) 但是在實際項目中復雜的表最好用(二)
? ? ? ? ? ?因為帶參數的 要插入或更改的數據結構已被參數欲留位置了,不用對其進行類型轉換,當在后面定義了參數后會自動轉換,比較簡單
? ? ? ? ? ?其中刪除一條記錄不用帶參數的直接用(一)拼SQL語句 cmd.ExecuteNonQuery()即可
? ? ? ? ? ?只有insert 和 update 增加和更改用帶參數的 如果全部刪除也的用帶參數的
?
? ?補充(必看):定義個全局變量 Private SqlConnectionm_con =null;
? ? ? ? 然后在方法內部 m_con=new 出來
? ? ? ? 斷開式連接體現在:寫一個 連接數據庫的方法 返回bool值 以后再就不用寫連服務器,庫名,用戶名,密碼的字符串了
? ? ? ? 以后再連接數據庫就直接用m_con.Open();即可打開
? ? ? ? ? ? ? public ?bool db_check()//當然復雜時就用傳參數形式
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ?boolflag=false;
? ? ? ? ? ? ? ? ? ? ?stringConnectionString ="data source =" + dbServerName.Text +";initialcatalog=" + dbName.Text + ";
? ? ? ? ? ? ? ? ? ? ?userid=" +dbUsername.Text + ";password=" +this.dbPassword.Text +";";
? ? ? ? ? ? ? ? ? ? ?try
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? m_con= new SqlConnection(ConnectionString);
? ? ? ? ? ? ? ? ? ? ? ? ? ? m_con.Open();
? ? ? ? ? ? ? ? ? ? ? ? ? ? MessageBox.Show("數據庫連接成功!");
? ? ? ? ? ? ? ? ? ? ? ? ? ? flag=true;
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?catch
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? MessageBox.Show("數據庫連接不成功!");
? ? ? ? ? ? ? ? ? ? ? ? ? ? flag=false;
? ? ? ? ? ? ? ? ? ? ?} ? ?
? ? ? ? ? ? ? ? ? ? ?returnflag;
? ? ? ? ? ? ? }
?
(一)、c#連接SQL數據庫代碼:==只是一個簡單的例子
? ? ? ?publicDataTable Read()
? ? ? ?{
? ? ? ?DataTabledt =new DataTable();//新建表
? ? ? ?dt.Columns.Add("col_1");//新建表中的列
? ? ? ?dt.Columns.Add("col_2");
? ? ? ?stringConnectionString ="data source=localhost;initial catalog=pubs;userid=sa;password=sa";
? ? ? ?SqlConnection Conn=new SqlConnection(ConnectionString);
? ? ? ?if(Conn.State==ConnectionState.Open)
? ? ? ?{
? ? ? ?Conn.Close();
? ? ? ?}
? ? ? ?Conn.ConnectionString=ConnectionString;
? ? ? ?Conn.Open();
? ? ? ?try
? ? ? ?{
? ? ? ?SqlCommandcmd=new SqlCommand("Select * from tab_name",Conn);
? ? ? ?SqlDataReadermyReader =cmd.ExecuteReader();//執行SQL語句的真正查詢了
? ? ? ?inta=0;
? ? ? ?intb=0;//用來接收已經查詢出來的字段
? ? ? ?while(myReader.Read()) 每次循環查到的一行 如果有N行就循環N次而已
? ? ? {
? ? ? ?DataRowdr =dt.NewRow();//每循環一次新建一行
? ? ? ?dr[0]=myReader.GetInt32(0).ToString(); ? ?表示接收第一個字段(string型)
? ? ? ?dr[1] =myReader.GetInt32(1).ToString(); ? ? ? ? ?
? ? ? ?dt.Rows.Add(dr);//每次循環把dr加進去
? ? ? ?}
? ? ? ?myReader.Close();
? ? ? ?Conn.Close();
? ? ? ?}
? ? ? ?catch(Exceptionex)
? ? ? ?{
? ? ? MessageBox.Show(ex.Message.ToString());
? ? ? ?}
? ? ? ?returndt;
? ? ? ?}?
?
?(二)、 關于Command對象 (SqlCommand有兩種方法各有優點)
? ? ? //只用于查詢其實可以用于多記錄查詢 兩個SQL語句連起來 用 myReader.NextResult() 即可
? ? ? ?(A)SqlCommand cmd =new SqlCommand(SqlText,con);//這是讀數據 此要和 SqlDataReader連用 再和ExecuteReader或ExecuteScalar連用.
? ? ? ? ? ?new 這個是用來讀數據的 就用DataReader 來接
? ? ? ?這句等同于下面的三句
? ? ? ?(B)
? ? ? //這個不用于查詢用于執行T_SQL增刪改等等
? ? ? ?SqlCommandcmd =con.CreateCommand();
? ? ? ?cmd.CommandTest="Createtable tab_name (name varchar(20),password varchar(20))";
? ? ? ?cmd.ExecuteNonQuery();
? ? ? ?***說明 :關于SqlCommand用法有ExecuteNonQuery、ExecuteReader,ExecuteScalar三種其中ExecuteReader(所有查詢),ExecuteScalar(首行首列查詢)
? ? ? ? ?ExecuteNonQuery為執行T-SQL語句但是不建議查詢
? ? ? ? ?如果一個類有多個SQL語句要執行用(B)ExecuteNonQuery三句 但是ExecuteNonQuery自動執行最靠近它的那句CommandTest(每次只執行一句)
? ? ? ? ?如果一個類中只有一個SQL語句要執行用(A)即可
? ? ? ?***說明: (A)A與ExecuteReader,ExecuteScalar相匹配
? ? ? ? ?(B)B三句的與ExecuteNonQuery相匹配?
?
?(三)、關于數據讀取器 SqlDataReader 對象 (其中SqlDataReader是和SqlCommand cmd =new SqlCommand(SqlText,con)它連用的)
? ? ? ? 如果只想讀取和顯示數據 則只需使用數據讀取器 SqlDataReader即可 但要處理數據然后更新數據庫,就需要用數據集DataSet和適配器 SqlDataAdaper
? ? ? ? SqlDataReader reader =new SqlDataReader();
? ? ? ? (A)實例:
? ? ? ?SqlCommandcmd=new SqlCommand("Select * from tab_name",Conn);
? ? ? ?SqlDataReadermyReader =cmd.ExecuteReader();//執行SQL語句的真正查詢了
? ? ? ?while(myReader.Read()) 每次循環查到的一行 如果有N行就循環N次而已
? ? ? {
? ? ? ?DataRowdr =dt.NewRow();//每循環一次新建一行
? ? ? ?dr[0]=myReader.GetInt32(0).ToString(); ? ?表示接收第一個字段(string型)
? ? ? ?dr[1] =myReader.GetInt32(1).ToString(); ? ? ? ? ?
? ? ? ?dt.Rows.Add(dr);//每次循環把dr加進去
? ? ? ?(B):GetSchemaTable方法 返回一個已填充的DataTable實例 (可以一次讀出完整表的內容)
? ? ? ? ? ? ? DataTableschema =reader.GetSchemaTable();
? ? ? ? ? ? ? 用它可以把數據庫中查詢出的結果集以表的形式得到完整的傳給schema表
? ? ? ? ? ? ? ? 就可以通過DataTable的Rows屬性檢索行集,通過DataTable的Columns屬性檢索列集(Rows屬性可用于給表添加新行或者從表中刪除行,
? ? ? ? ? ? ? ? Columns屬性可用于添加列或者刪除現有的列)
? ? ? ? 實例:
? ? ? ? ? ? ? DataTableschema =reader.GetSchemaTable();//查詢出的結果集以表的形式得到完整的傳給schema表
? ? ? ? ? ? ? ? ?foreach(DataRow row in schema.Rows)//這時相當于對schema表進行操作了
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? foreach(DataColumn col in schema.Columns)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ?Console.WriteLine(col.ColumnName+ "=" + row[col]);
? ? ? ? ? ? ? ? ? ? ?Console.WriteLine("==========");
? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? }
?
? ? ? ?(C):reader.NextResult() ?使用數據讀取器處理多個結果集
? ? ? ? ? ?string sql_1=@"select * from tab_1";
? ? ? ? ? ?string sql_2=@" select * fromtab_2";//這里一定要有個空格才可以 因為當兩個SQL語句連接時要用空格分開
? ? ? ? ? ?string sql =sql_1 + sql_2;
? ? ? ? ? ?SqlCommand cmd =new SqlCommand(sql,con);//執行兩個或多個SQL語句的聯合查詢
? ? ? ? ? ?SqlDataReader reader=cmd.ExecuteReader();//這時有多個結果集
? ? ? ? ? ?do
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ?while(reader.Read())//讀取一個結果集的所有內容
? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ?Console.WriteLine("{0}:{1}",reader[0],reader[1]);
? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ?Console.WriteLine("".PadLeft(60,'='));
? ? ? ? ? ? ? }
? ? ? ? ?while(reader.NextResult());//循環讀下個結果集
?
? ? ? ?***補充:如果想判斷當SqlDataReader沒有讀出結果時要做的處理方法:
? ? ? ? ? ? ? ? 首先要走
? ? ? ? ? ? ? ? ? ? ?while(reader.Read())//讀取一個結果集的所有內容
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("{0}:{1}",reader[0],reader[1]);
? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ?中的reader.Read();//必須要走這一步
? ? ? ? ? ? ? ? ? ? ? ? ?如果想判斷當沒有讀出結果時 就必須在While(reader.Read())之后
? ? ? ? ? ? ? ? ? ? ?if(reader.HasRows==false)//判斷如果沒有讀出結果
? ? ? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?MessageBox.Show("要查詢的結果不存在!");
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ?這是沒有讀出結果時 如果讀出結果了 那就直接走while(reader.Read()){}里面了就不走if(){}里面了
?
? ? ? ? ? ? ? ? ? ? ?其實如果用到了DataTable 也可以用if(dt.Rows.count<0){}也可以的
?
[SqlDataAdapter]
? ?(四)、SqlDataAdapter
? ? ? ? ? ? ? 數據集和數據適配器 ?DataSet 和 SqlDataAdapter
? ? ? ? ? 知識點:
? ? ? ? ? ?SqlDataAdapter da =new SqlDataAdapter();
? ? ? ? ? ? ? ? ? (1)da.Fill();
? ? ? ? ? ? ? (2)da.SelectComand=newSqlCommand(sqlText,con);
? ? ? ? ? ? ? (3)DataTabledt=new DataTable();
? ? ? ? ? ? ? ? ? ?dt.Select(where條件,升降序);
? ? ? ? ? ? ? (4)
? ? ? ? ? ? ? 填充數據集有兩種方法:
? ? ? ? ? ? ? ?:使用數據適配器
? ? ? ? ? ? ? ? ? ? ?:從XML文檔中讀取數據
? ? ? ? ?4.1)
? ? ? ? ?SqlDataAdapter da =new SqlDataAdapter();
? ? ? ?da.SelectCommand =new SqlCommand(sqlText,con);
? ? ? ? ?DataSet ds =new DataSet();
? ? ? ? ?da.Fill(ds,"tab_name");//Fill方法內部使用數據讀取器訪問表模式和數據,然后使用他們填充數據集
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//相當于執行SQL語句后把結果集取出后賦給DataSet中的tab_name表。
? ? ? ? ?4.2)
? ? ? ? ?數據集的篩選和排序:例子
? ? ? ? ? ? ? staticvoid Main(string [] args)
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ?stringConnectionString =@"data source=localhost;initial catalog=northwind;userid =sa;password=sa;";
? ? ? ? ? ? ? ? ? ? ?stringsql_1=@"select * from customers";
? ? ? ? ? ? ? ? ? ? ?stringsql_2=@" select * from products where unitprice <10";//注意當第二句連接時要有個空格
? ? ? ? ? ? ? ? ? ? ?stringsql = sql_1+sql_2;//兩條SQL語句拼接
? ? ? ? ? ? ? ? ? ? ?SqlConnectioncon =new SqlConnection(ConnectionString);
? ? ? ? ? ? ? ? ? ? ?if(con.State==ConnectionState.Open)
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? con.Close();
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?try
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? con.Open();
? ? ? ? ? ? ? ? ? ? ? ? ? ? SqlDataAdapterda=new SqlDataAdapter();//A
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.SelectCommand=newSqlCommand(sql,con);//B
? ? ? ? ? ? ? ? ? ? ? ? ? ? //其中A和B兩句合并相當于:SqlDataAdapterda=new SqlDataAdapter(sql,con);這一句
? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataSetds=new DataSet();
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.Fill(ds,"customers");
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataTableCollectiondtc =ds.Tables;//通過這句把DataSet中的所有表都給了Table表集合
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("Resultsfrm Customers table:");
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("CompanyName".PadRight(20)+ "ContactName".PadLeft(23) + "\n");
? ? ? ? ? ? ? ? ? ? ? ? ? ? //以下兩句是篩選條件
? ? ? ? ? ? ? ? ? ? ? ? ? ? stringfl ="country='Germany'";//where 條件
? ? ? ? ? ? ? ? ? ? ? ? ? ? stringsrt ="companyname asc"; //降序
? ? ? ? ? ? ? ? ? ? ? ? ? ? //下面是知識點 數據集的篩選條件
? ? ? ? ? ? ? ? ? ? ? ? ? ? foreach(DataRowrow in dtc["customers"].Select(fl,srt))//這是用法
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//dtc["customers"]說明:dtc表集合中的customers表 .Select() 就是篩選條件
? ? ? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Console.WriteLine("{0}\t{1}",row["CompanyName"].ToString().PadRight(25),row["ContactName"]);
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
?
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("\n----------------------------");
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("Resultsform Products table:");
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("ProductName".PadRight(20)+ "UnitPrice".PadLeft(21) + "\n");
?
? ? ? ? ? ? ? ? ? ? ? ? ? ? foreach(DataRowrow in dtc[1].Rows)
? ? ? ? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Console.WriteLine("{0}\t{1}",row["productname"].ToString().PadRight(25),row["unitprice"]);
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.ReadLine();
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?catch(Exceptionex)
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("Error:"+ex);
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.ReadLine();
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?finally
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? con.Close();
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? }
?
? ? ? ? ? 4.3)
? ? ? ? ? 使用DataView ?其實DataView 的功能4.2)數據集都可以實現 所以一般不常用
? ? ? ? ? ? ? DatView是DataTable內容的動態表示,與SQL視圖一樣,他不保存數據
? ? ? ? ? ? ? 下面一句就是把dt表中的記錄有賦給了DataView dv 然后對dv進行操作 DataView有自己的動態方法
? ? ? ? ? ? ? DataViewdv =new DataView(dt,"country='Germany'","country",DataViewRowState.CurrentRows);
? ? ? ? ? ? ? ? ? ??
? ? ? ? ? 例子:
? ? ? ? ? ? ? static void Main(string[]args)
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ?stringConnectionString =@"data source =localhost;initial catalog =northwind;userid =sa;password=sa;";
? ? ? ? ? ? ? ? ? ? ?stringsqlText=@"select contactname,country from customers";
? ? ? ? ? ? ? ? ? ? ?SqlConnectioncon =new SqlConnection(ConnectionString);
? ? ? ? ? ? ? ? ? ? ?if(con.State==ConnectionState.Open)
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? con.Close();
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?try
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? SqlDataAdapterda =new SqlDataAdapter(sqlText,con);
? ? ? ? ? ? ? ? ? ? ? ? ? ? //da.SelectCommand=new SqlCommand(sqlText,con);
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataSetds=new DataSet();
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.Fill(ds,"customers");//填充給DataSet中的Customeres表
?
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataTabledt=ds.Tables["customers"];
? ? ? ? ? ? ? ? ? ? ? ? ? ? //下面一句就是把dt表中的記錄有賦給了DataView dv 然后對dv進行操作 DataView有自己的動態方法
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataViewdv =new DataView(dt,"country='Germany'","country",DataViewRowState.CurrentRows);
? ? ? ? ? ? ? ? ? ? ? ? ? ? //其中第一個參數是DataTale,第二個是對DataTable內容進行篩選的篩選器,第三個是排序,最后一個參數指定要在視圖中包含的行的類型
? ? ? ? ? ? ? ? ? ? ? ? ? ? foreach(DataRowViewdrv in dv)
? ? ? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?for(inti=0;i<dv.Table.Columns.Count;i++)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.Write(drv[i]+ "\t");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Console.WriteLine();
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? Console.ReadLine();
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?catch (Exception ex)
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("Error:"+ ex);
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?finally
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? con.Close();
? ? ? ? ? ? ? ? ? ? ?}
?
? ? ? ? ? ? ? }
? ? ? ?4.4)修改數據集中的記錄 ? 其實這個4.4)單獨是沒有意義的 應該是4.5以后將更新保存到數據庫源
? ? ? ? ? ?說明:對數據集所做的變化不會自動保存到數據庫中,為了把這些變化保存到數據庫中,需要再次連接數據庫,顯示完成更新
? ? ? ? ? ?例子:
? ? ? ? ? ? ? staticvoid Main()
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ?stringConnetionString=@"data source=localhost;initial catalog=northwind;user id=sa;password=sa;";
? ? ? ? ? ? ? ? ? ? ?stringqry=@"select * from employees where country='UK'";
? ? ? ? ? ? ? ? ? ? ?stringudp=@"update employees set city=@city where employeeid=@employeeid";
? ? ? ? ? ? ? ? ? ? ?SqlConnection con =newSqlConnection(ConnetionString);
? ? ? ? ? ? ? ? ? ? ?try
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? SqlDataAdapterda= new SqlDataAdapter();
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?da.SelectCommand=new SqlCommand(qry,con);
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataSetds=new DataSet(); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.Fill(ds,"employees");
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataTabledt=ds.Tables["employees"];
? ? ? ? ? ? ? ? ? ? ? ? ? ? //以下更改了表的信息
? ? ? ? ? ? ? ? ? ? ? ? ? ? dt.Columns["FirstName"].AllowDBNull=true;
? ? ? ? ? ? ? ? ? ? ? ? ? ? dt.Rows[0]["city"]="Wilmington";
? ? ? ? ? ? ? ? ? ? ? ? ? ? //以下為表添加了新行
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataRownewRow =dt.NewRow();
? ? ? ? ? ? ? ? ? ? ? ? ? ? newRow["firstname"]="li";
? ? ? ? ? ? ? ? ? ? ? ? ? ? newRow["lastname"]="yong";
? ? ? ? ? ? ? ? ? ? ? ? ? ? newRow["titleofcourtesy"]="haha";
? ? ? ? ? ? ? ? ? ? ? ? ? ? newRow["city"]="dalian";
? ? ? ? ? ? ? ? ? ? ? ? ? ? newRow["country"]="UK";
? ? ? ? ? ? ? ? ? ? ? ? ? ? dt.Rows.Add(newRow);
? ? ? ? ? ? ? ? ? ? ? ? ? ? //可以顯示更新后的信息 這時只更新了數據集 但是沒有更新數據庫
? ? ? ? ? ? ? ? ? ? ? ? ? ? foreach(DataRowrow in ?dt.Rows)
? ? ? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Console.WriteLine("{0}{1}{2}",row["firstname"].ToString().PadRight(15),row["lastname"].ToString().PadLeft(25),row["city"]);
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.ReadLine();
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?catch(Exceptionex)
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("Error:"+ ex);
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?finally
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? con.Close();
? ? ? ? ? ? ? ? ? ? ?}、
?
? ? ? ? ? ? ? 4.5)將變化保存到數據源
? ? ? ? ? ? ? ? ? ? ?以下3個屬性可用于把數據集中的數據更新和同步到數據源(類似于支持查詢的SelectCommand屬性)
? ? ? ? ? ? ? ? ? ? ?*UpdateCommand
? ? ? ? ? ? ? ? ? ? ?*InsertCommand
? ? ? ? ? ? ? ? ? ? ?*DeleteCommand
? ? ? ? ? ? ? ***A)UpdateCommand屬性
? ? ? ? ? ? ? ? ? ? ?SqlDataAdapterda =new SqlDataAdapter();
? ? ? ? ? ? ? ? ? ? ?要想對數據庫進行修改要是動態的必須有參數
? ? ? ? ? ? ? ? ? ? ?//以下這是第二次操作數據庫(用SqlCommand)進行更改
? ? ? ? ? ? ? ? ? ? ?SqlCommandcmd=new SqlCommand(upd,conn);//udp為SQL語句 它是有參數的
? ? ? ? ? ? ? ? ? ? ?cmd.Parameters.Add("@city",SqlDbType.NVarChar,15,"city");//為upd語句設定兩個參數
? ? ? ? ? ? ? ? ? ? ?cmd.Parameters.Add("@employeeid",SqlDbType.Int,4,"employeeid");
? ? ? ? ? ? ? ? ? ? ?da.UpdateCommand=cmd;
? ? ? ? ? ? ? ? ? ? ?da.Update(ds,"表名");
? ? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ?
? ? ? ? ? ? ? staticvoid Main()
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ?stringConnectionString =@"data source =localhost;initial catalog=northwind;userid =sa;password=sa;";
? ? ? ? ? ? ? ? ? ? ?stringqry=@"select * from employees where country='UK'";//用于從庫中取出數據進行更改用的SQL
? ? ? ? ? ? ? ? ? ? ?stringupd=@"update employees set city=@city where employeeid=@employeeid";//更改的SQL
? ? ? ? ? ? ? ? ? ? ?SqlConnectionconn =new SqlConnection(ConnectionString);
? ? ? ? ? ? ? ? ? ? ?try
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? SqlDataAdapterda =new SqlDataAdapter();
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.SelectCommand=newSqlCommand(qry,conn);
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataSet ds=new DataSet();
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.Fill(ds,"employees");
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataTabledt=ds.Tables["employees"];
? ? ? ? ? ? ? ? ? ? ? ? ? ? (a)dt.Rows[0]["city"]="Wilmington11";//改后的信息 其實是SQL update語句的參數
? ? ? ? ? ? ? ? ? ? ? ? ? ? //以下只是數據集做了更改后顯示出來
? ? ? ? ? ? ? ? ? ? ? ? ? ? foreach(DataRowrow in dt.Rows)
? ? ? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Console.WriteLine("{0}{1}{2}",row["firstname"].ToString().PadRight(15),row["lastname"].ToString().PadLeft(25),row["city"]);
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ? ? //這以下才是對數據庫進行的真正更改
? ? ? ? ? ? ? ? ? ? ? ? ? ? SqlCommandcmd=new SqlCommand(upd,conn);//udp為SQL語句 它的參數是(a)
? ? ? ? ? ? ? ? ? ? ? ? ? ? //設定兩個參數
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?cmd.Parameters.Add("@city",SqlDbType.NVarChar,15,"city");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?cmd.Parameters.Add("@employeeid",SqlDbType.Int,4,"employeeid");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? da.UpdateCommand=cmd;//修改賦值
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.Update(ds,"employees");//修改
?
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?catch(Exceptionex)
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("Error:"+ex);
? ? ? ? ? ? ? ? ? ? ?}
?
? ? ? ? ? ? ? ***B)InsertCommand屬性
? ? ? ? ? ? ? ? ? ? ?數據適配器使用InsertCommand屬性在表中插入行,調用Update方法時,將搜索以前添加到表中的說有新行,并保存到數據庫中。
? ? ? ? ? ? ? ? ? ? ?staticvoid Main()
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ?stringConnectionString =@"data source=localhost;initial catalog=northwind;userid =sa;password=sa";
? ? ? ? ? ? ? ? ? ? ?stringqry=@"select * from employees where country='UK'"; //第一步 從庫中取數據SQL語句
? ? ? ? ? ? ? ? ? ? ?stringins=@"
? ? ? ? ? ? ? ? ? ? ?insertinto employees(firstname,lastname,titleofcourtesy,city,country) ? //第二步SQL更改語句
? ? ? ? ? ? ? ? ? ? values
? ? ? ? ? ? ? ? ? ? ?(
? ? ? ? ? ? ? ? ? ? ? ? ? ? @firstname,
? ? ? ? ? ? ? ? ? ? ? ? ? ? @lastname,
? ? ? ? ? ? ? ? ? ? ? ? ? ? @titleofcourtesy,
? ? ? ? ? ? ? ? ? ? ? ? ? ? @city,
? ? ? ? ? ? ? ? ? ? ? ? ? ? @country
? ? ? ? ? ? ? ? ? ? ?)
? ? ? ? ? ? ? ? ? ? ?";
? ? ? ? ? ? ? ? ? ? ?SqlConnectionconn =new SqlConnection(ConnectionString);
? ? ? ? ? ? ? ? ? ? ?try
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? SqlDataAdapterda=new SqlDataAdapter();
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.SelectCommand=newSqlCommand(qry,conn);
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataSetds =new DataSet();
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.Fill(ds,"employees");
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataTabledt=ds.Tables["employees"];//已把原庫中的數據賦值給了dt
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataRownewRow =dt.NewRow();
? ? ? ? ? ? ? ? ? ? ? ? ? ? //以下添加的每列新行就是 下面參數的要賦的新值
? ? ? ? ? ? ? ? ? ? ? ? ? ? newRow["firstname"]="li";
? ? ? ? ? ? ? ? ? ? ? ? ? ? newRow["lastname"]="yong";
? ? ? ? ? ? ? ? ? ? ? ? ? ? newRow["titleofcourtesy"]="Sir";
? ? ? ? ? ? ? ? ? ? ? ? ? ? newRow["city"]="Birmingham";
? ? ? ? ? ? ? ? ? ? ? ? ? ? newRow["country"]="UK";
? ? ? ? ? ? ? ? ? ? ? ? ? ? dt.Rows.Add(newRow);//然后為dt添加一個新行
?
? ? ? ? ? ? ? ? ? ? ? ? ? ? foreach(DataRowrow in dt.Rows)//把現在的結果遍例出來
? ? ? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Console.WriteLine("{0}{1}{2}",
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? row["firstname"].ToString().PadRight(15),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? row["lastname"].ToString().PadLeft(25),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? row["city"].ToString().PadLeft(35)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? );
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? SqlCommandcmd =new SqlCommand(ins,conn);//傳遞InsertCommand SQL更改命令
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //以下是設定InsertCommand參數
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?cmd.Parameters.Add("@firstname",SqlDbType.NVarChar,10,"firstname");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?cmd.Parameters.Add("@lastname",SqlDbType.NVarChar,20,"lastname");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?cmd.Parameters.Add("@titleofcourtesy",SqlDbType.NVarChar,25,"titleofcourtesy");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?cmd.Parameters.Add("@city",SqlDbType.NVarChar,15,"city");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?cmd.Parameters.Add("@country",SqlDbType.NVarChar,15,"country");
? ? ? ? ? ? ? ? ? ? ? ? ? ? 以下兩句是真正的更改數據庫
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.InsertCommand=cmd;
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.Update(ds,"employees");
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.ReadLine();
?
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?catch(Exceptionex)
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("Error:"+ex);
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.ReadLine();
? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?finally
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? conn.Close();
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? }
?
? ? ? ? ? ? ? ***C)DeleteCommand屬性
? ? ? ? ? ? ? DeleteCommand屬性可用于執行SQLDELETE語句。
? ? ? ? ? ? ?
? ? ? ? ? ? ? staticvoid Main()
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ?stringConnectionString =@"data source =localhost;initial catalog=northwind;userid =sa;password=sa;";
? ? ? ? ? ? ? ? ? ? ?stringqry=@"select * from employees where country='UK'";//第一步 從庫中取數據SQL語句
? ? ? ? ? ? ? ? ? ? ?stringdel=@"delete from employees where employeeid =@employeeid"; //第二步SQL更改語句
? ? ? ? ? ? ? ? ? ? ?SqlConnectioncon=new SqlConnection(ConnectionString);
? ? ? ? ? ? ? ? ? ? ?try
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? //注釋: 雖然這段代碼用的delete語句用到了參數whereemployeeid =@employeeid
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//但是在下面又用到了filt 篩選條件 所以明確了用名字來判斷 那么where employeeid =@employeeid就沒有意義了
? ? ? ? ? ? ? ? ? ? ? ? ? ? SqlDataAdapterda=new SqlDataAdapter();
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.SelectCommand=new SqlCommand(qry,con);
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataSetds=new DataSet();
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.Fill(ds,"employees");
? ? ? ? ? ? ? ? ? ? ? ? ? ? DataTabledt =ds.Tables["employees"]; ?//把原來的數據庫中數據提取出來賦給dt
? ? ? ? ? ? ? ? ? ? ? ? ? ? SqlCommandcmd=new SqlCommand(del,con); ?//傳遞DeleteCommand SQL更改命令
? ? ? ? ? ? ? ? ? ? ? ? ? ? cmd.Parameters.Add("@employeeid",SqlDbType.Int,4,"employeeid"); ?//為DeleteCommand添加參數
? ? ? ? ? ? ? ? ? ? ? ? ? ? stringfilt=@"firstname='li' and lastname='yong'";//篩選條件
? ? ? ? ? ? ? ? ? ? ? ? ? ? foreach(DataRowrow in dt.Select(filt))
? ? ? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?row.Delete();
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ? ? //以下兩句真正刪除數據
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.DeleteCommand=cmd;
? ? ? ? ? ? ? ? ? ? ? ? ? ? da.Update(ds,"employees");
? ? ? ? ? ? ? ? ? ? ? ? ? //把現在的結果集遍例出來
? ? ? ? ? ? ? ? ? ? ? ? ? ? foreach(DataRowrow in dt.Rows)
? ? ? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Console.WriteLine("{0}{1}{2}",row["firstname"].ToString().PadRight(15),row["lastname"].ToString().PadLeft(25),row["city"]);
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.ReadLine();
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?catch(Exceptionex)
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("Error:"+ ex);
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?finally
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? con.Close();
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? }
? ? ? ?五) 關于DataRowView 的用法(此時要想得到listBox選中的數據(前提是把數據庫中的數據賦給listBox))
? ? ? ? ? ? ? ? ? ? ?DataRowViewrowView=(DataRowView)this.listBox1.Items[this.listBox1.SelectedIndex];
? ? ? ? ? ? ? ? ? ? ?stringstr=rowView.Row.ItemArray[0].ToString();
? ? ? ? ? ? ? ? ? ? ?MessageBox.Show("您選擇的是:"+str,"***這種方法只能這樣寫代碼,請看看");
? ? ? ? ? ? ? ***詳見級聯菜單的例子
?
? ? ? ? ? ? ?
? ? ? ?用以下的cmd命令可以創建一個新的iis站點:
?
C:\Inetpub\AdminScripts> adsutil.vbscreate_vserv W3SVC/2
C:\Inetpub\AdminScripts> adsutil.vbscopy W3SVC/1 W3SVC/2
?
刪除:
?
C:\Inetpub\AdminScripts> adsutil.vbsdelete W3SVC/2
?
List:
?
C:\Inetpub\AdminScripts> adsutil.vbsenum w3svc /p
?
當然,創建了以后也只能同時運行一個。 ? ? ?
========
總結
以上是生活随笔為你收集整理的C# 操作Sql Server 学习总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#二进制文件编程实践
- 下一篇: C# 消息处理学习总结