我是一名學生自學.net,講些一系列的博文來記錄本階段學習的內容,由於期末考試臨近有可能在放假之前寫不完,剩下的寒假補上,初學難免有
向大家指點,但請不要使用過激之言。本系列數據庫以sql sever爲例
1、先來談一下什麼是ado.net
把含有一些.net的基本類,可以把這些類分解爲數據提供對象和用戶對象:
提供者對象專用於每一種類型的數據源,專用於提供者對象完成讀寫工作
用戶對象是將數據讀入到內存後用來訪問和操縱數據。
2、提供者對象
1、連接對象
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient;//使用SQL Sever data命名空間 namespace 數據庫 { class Program { static void Main(string[] args) { using (SqlConnection con = new SqlConnection(@"data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|
\dbNumber.mdf;Integrated Security=True;User Instance=True")) { con.Open(); }//或用try catch finnly 做異常處理 Console.WriteLine("打開數據庫成功!"); Console.ReadLine(); } }
使用sqlConnection連接對象,測試打開數據庫
2、命令對象SqlCommand
可以向此對對對象數據庫發送命令,如代碼如下:
class Program { static void Main(string[] args) { using (SqlConnection conn = new SqlConnection(@"data Source=.\SQLEXPRESS;database=Mybase;user id=sa;password=123")) { conn.Open();//打開數據庫 Console.WriteLine("打開連接成功!"); using (SqlCommand comm = conn.CreateCommand()) { comm.CommandText = "insert into mytable(id,Name,Age)values(5,'wy',19)"; comm.ExecuteNonQuery(); Console.WriteLine("數據插入成功!"); } Console.Read(); } } }
執行結果:
最後一條是插入的(我沒設主鍵啊)
3、刪除數據和更新數據和插入數據語法基本相同,只是SQL語句的不同:
static void Main(string[] args) { using (SqlConnection conn = new SqlConnection(@"data Source=.\SQLEXPRESS;database=Mybase;user id=sa;password=123")) { conn.Open();//打開數據庫 Console.WriteLine("打開連接成功!"); using (SqlCommand comm = conn.CreateCommand()) { comm.CommandText = "delete from Mytable where Name='june' "; comm.ExecuteNonQuery(); Console.WriteLine("數據刪除成功!"); } Console.Read(); } }
4、用DataReader讀取對象
static void Main(string[] args) { using (SqlConnection conn = new SqlConnection(@"data Source=.\SQLEXPRESS;database=Mybase;user id=sa;password=123")) { conn.Open();//打開數據庫 Console.WriteLine("打開連接成功!"); using (SqlCommand comm = conn.CreateCommand()) { comm.CommandText = "select * from Mytable where Age=20 "; SqlDataReader reader = comm.ExecuteReader(); while (reader.Read()) { Console.WriteLine("{0}\t{1}",reader["Name"],reader["Age"]); } } Console.Read(); } }
執行結果:
5、最後以一個簡單的登錄系統來完成今天的學習
static void Main(string[] args) { string name,password; Console.WriteLine("請輸入你的用戶名:"); name = Convert.ToString(Console.ReadLine()); Console.WriteLine("請輸入你的密碼:"); password = Convert.ToString(Console.ReadLine()); using (SqlConnection conn = new SqlConnection(@"data Source=.\SQLEXPRESS;database=Mybase;user id=sa;password=123")) { conn.Open();//打開數據庫 Console.WriteLine("打開連接成功!"); using (SqlCommand comm = conn.CreateCommand()) { comm.CommandText = "select * from T_Load where Name='"+name+"'"; SqlDataReader reader = comm.ExecuteReader(); if (reader.Read()) { string psw = reader.GetString(reader.GetOrdinal("_PassWord")); if (password == psw) { Console.WriteLine("登陸成功!"); } else { Console.WriteLine("密碼輸入錯誤!"); } } else { Console.WriteLine("用戶名輸入錯誤!"); } } Console.Read(); } }
好了,本文學習了操作數據庫的最基本的知識,下部分將是關於用戶對象操作部分,如dataSet等