C# ado.net 操作(一)
简单的增删改查
1 class Program 2 { 3 private static string constr = "server=.;database=northwnd;integrated security=sspi"; 4 static void Main(string[] args) 5 { 6 ExecuteXmlReader(); 7 ExecuteScalar(); 8 ExecuteReader(); 9 ExecuteNonQuery(); 10 } 11 public static void ExecuteNonQuery() 12 { 13 string select = "update customers set contactname='bob' where contactname='Maria Anders'"; 14 SqlConnection con = new SqlConnection(constr); 15 con.Open(); 16 SqlCommand cmd = new SqlCommand(select, con); 17 int rows = cmd.ExecuteNonQuery(); 18 Console.WriteLine("{0} rows returned",rows); 19 con.Close(); 20 } 21 public static void ExecuteReader() 22 { 23 string select = "select contactname,companyname from customers"; 24 SqlConnection con = new SqlConnection(constr); 25 con.Open(); 26 SqlCommand cmd = new SqlCommand(select, con); 27 SqlDataReader reader = cmd.ExecuteReader(); 28 while (reader.Read()) 29 { 30 Console.WriteLine("Contact: {0,-24} Company: {1}", 31 reader[0], reader[1]); 32 } 33 } 34 static void ExecuteScalar() 35 { 36 string select = "SELECT COUNT(*) FROM Customers"; 37 SqlConnection conn = new SqlConnection(constr); 38 conn.Open(); 39 SqlCommand cmd = new SqlCommand(select, conn); 40 object o = cmd.ExecuteScalar(); 41 Console.WriteLine(o); 42 } 43 44 static void ExecuteXmlReader() 45 { 46 string select = "SELECT ContactName,CompanyName " + 47 "FROM Customers FOR XML AUTO"; 48 SqlConnection conn = new SqlConnection(constr); 49 conn.Open(); 50 SqlCommand cmd = new SqlCommand(select, conn); 51 XmlReader xr = cmd.ExecuteXmlReader(); 52 xr.Read(); 53 string data; 54 do 55 { 56 data = xr.ReadOuterXml(); 57 if (!string.IsNullOrEmpty(data)) 58 Console.WriteLine(data); 59 } while (!string.IsNullOrEmpty(data)); 60 conn.Close(); 61 62 } 63 64 } 65 }
鹰击长空,鱼翔浅底