標籤:style blog http io color ar os sp 資料
ado.net串連sql server2008本機資料庫
1.只串連資料庫,然後做簡單查詢
1 using (SqlConnection conn = new SqlConnection("Data Source=127.0.0.1; Initial Catalog=MyTest;User ID=sa;Password=123456"))2 {3 conn.Open();4 using (SqlCommand cmd = conn.CreateCommand())5 {6 long i = (long)cmd.ExecuteScalar();//bigint→long7 MessageBox.Show(i.ToString());8 }9 }
2.能完成一般的資料庫連接,實現增刪改查準系統
1 using System.Windows.Controls; 2 using System.Windows.Data; 3 using System.Windows.Documents; 4 using System.Windows.Input; 5 using System.Windows.Media; 6 using System.Windows.Media.Imaging; 7 using System.Windows.Navigation; 8 using System.Windows.Shapes; 9 using System.Data.SqlClient;10 11 namespace ADONET基礎12 {13 /// <summary>14 /// MainWindow.xaml 的互動邏輯15 /// </summary>16 public partial class MainWindow : Window17 {18 public MainWindow()19 {20 InitializeComponent();21 }22 23 private void button1_Click(object sender, RoutedEventArgs e)24 {25 //IDisposible26 //using(類型 d = new ....)27 //{.....................}28 29 //SqlConnection為建立和資料庫連接的對象30 //using (SqlConnection conn = new SqlConnection(31 // "Data Source=127.0.0.1; Initial Catalog=MyTest;User ID=sa;Password=123456"))32 //{33 // conn.Open();//開啟串連34 // //通過串連建立一個向資料庫發命令(Command)的對象SqlCommand35 // using (SqlCommand cmd = conn.CreateCommand())36 // {37 // //CommandText為要執行的SQL語句38 39 // cmd.CommandText = "Insert into T_Student(Name,Age) values(‘元芳‘,2100)";40 // cmd.ExecuteNonQuery();//執行41 // } 42 //}43 44 //ExecuteNonQuery一般用來執行Update、Delete、Insert語句45 46 using (SqlConnection conn = new SqlConnection("Data Source=127.0.0.1; Initial Catalog=MyTest;User ID=sa;Password=123456"))47 {48 conn.Open();49 using (SqlCommand cmd = conn.CreateCommand())50 {51 //cmd.CommandText = "select count(*) from T_Student where Age<100";52 //int i = (int)cmd.ExecuteScalar();53 //MessageBox.Show(i+"條資料");54 55 //cmd.CommandText = "select ‘aaa‘";56 ////ExecuteScalar一般用來執行有且只有一行一列傳回值的SQL語句57 //string s = (string)cmd.ExecuteScalar();58 //MessageBox.Show(s);59 60 //獲得自增欄位的值61 //cmd.CommandText = "insert into T_Student(Name,Age) values(‘aaa‘,123) ;select @@identity";62 // cmd.CommandText = "insert into T_Student(Name,Age) output inserted.Id values(‘aaa‘,123) ";63 long i = (long)cmd.ExecuteScalar();//bigint→long64 MessageBox.Show(i.ToString());65 }66 }67 68 //MessageBox.Show("執行完成");69 }70 }71 }
View Code
第一個ADO.NET串連SQl server資料庫