首页 > 代码库 > 第一个ADO.NET连接SQl server数据库
第一个ADO.NET连接SQl server数据库
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 }
第一个ADO.NET连接SQl server数据库
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。