C#连接和查询Sql server数据库
上一篇 / 下一篇 2008-06-06 15:27:27 / 个人分类:C# Programming
51Testing软件测试网8u2{}8B5_'D@E!\
N8SG
@*W0using System;51Testing软件测试网tL7zSeO
using System.Data;51Testing软件测试网|`kJ-?(kll-r
using System.Data.SqlClient;51Testing软件测试网2vm$nc'O#y2VY
using System.Collections.Generic;51Testing软件测试网s!yT-m6|0@Ck/L.n
using System.Text;51Testing软件测试网[2xJ,c
S8I
+Bilj"U0namespace 数据库学习
ub4ZYAHG0{51Testing软件测试网hG/aO c!Sc
class Program
q7zU{Q-ec0 {51Testing软件测试网e.VRc*W4|5w[
static void Main(string[] args)51Testing软件测试网2[
R3zW
{
{
//使用轻量级的SqlDataReader显示数据51Testing软件测试网8FCJJ k2CE
//指定Sql Server提供者的连接字符串51Testing软件测试网3QI,rb[)N1~cb
string connString = "server=192.168.99.45;database =northwind;uid =sa;pwd=1";51Testing软件测试网
qTX;O2bP)y&~|
1H%nY#y d$}0 //建立连接对象51Testing软件测试网l xvk9X@4aj2l
(~:S0R/eg0 SqlConnection Sqlconn = new SqlConnection(connString);
[5b[,^}b0 //打开连接
m^k\C+|h0 Sqlconn.Open();51Testing软件测试网;sd,tV ~ SK%jd8J
pJ
////为上面的连接指定Command对象51Testing软件测试网Q6[:G-xL"_K
//SqlCommand thiscommand = Sqlconn.CreateCommand();51Testing软件测试网6r R#P8S$U0`,bl
//thiscommand.CommandText = "select customerID,companyName from customers";51Testing软件测试网\X9a?"@XG
"D+b\4i X:P R _6`0 ////为指定的command对象执行DataReader51Testing软件测试网dNw/q
^-c
//SqlDataReader thisSqlDataReader = thiscommand.ExecuteReader();
8bu4z.x,{y0{"R"A0 ////只要有数据
U8XY4_,P_0 //while (thisSqlDataReader.Read())
(ft(y4W9A;h0 //{
:t#D
l9O&y`G1wZ0 ////输出数据51Testing软件测试网9?]UEp2y
// Console.WriteLine("\t{0}\t{1}", thisSqlDataReader["customerId"], thisSqlDataReader["companyName"]);51Testing软件测试网X;TO)_1\
//}
v-KR3D6r%g0 ////关闭读取
1X4Y.yXP!d
B0 //thisSqlDataReader.Close();
,gh-Vc*V0 ////关闭连接51Testing软件测试网1L3U
r dK
//Sqlconn.Close();
'A$MVR1s#V&P@6PR0 //Console.ReadLine();51Testing软件测试网
E Dai5kngz0M?
//使用dataset显示数据
'q8^#cH XS Qrp)_*S"K A0,a|cZPvr1? o0 // 查询字符串
0\S9k:f%y%v0 string thisCommand = "select customerID,companyName from customers";
//创建SqlDataAdapter对象,有两个参数,一个是查询字符串,一个是连接对象51Testing软件测试网$r|,L3NGRn\-p`(D;G
SqlDataAdapter SqlDap = new SqlDataAdapter(thisCommand,Sqlconn);
?0IN*Jt L0
fY_{y)IA%Z0 //创建DataSet对象
Bvs;u&a4dQ0 DataSet thisDataset = new DataSet();
b\3yUMuLE0 51Testing软件测试网MI7PC.j
//使用SqlDataAdapter的Fill方法填充DataSet,有两个参数,一个是创建的DataSet实例,一个是填入的表