ado.net连接sql server2008本机数据库
1.只连接数据库,然后做简单查询
微软文档SqlConnecttion :http://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqlconnection.aspx
SqlCommand:http://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx
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 Console.WriteLine("代码运行到了这里,连接成功!!"); 7 Console.ReadKey(); 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 : Window 17 { 18 public MainWindow() 19 { 20 InitializeComponent(); 21 } 22 23 private void button1_Click(object sender, RoutedEventArgs e) 24 { 25 //IDisposible 26 //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)的对象SqlCommand 35 // 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→long 64 MessageBox.Show(i.ToString()); 65 } 66 } 67 68 //MessageBox.Show("执行完成"); 69 } 70 } 71 }