1、建立连接数据库
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Data; 6 using System.Data.SqlClient; 7 8 9 namespace 连接数据库 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { //要连接数据库就要一个连接字符串,连接数据库的实例名,数据库名,用户名和密码 15 //string sqlConn = @"server=.\sqlexpress;database=MyDataBase;uid=sa;pwd=123"; 16 //string sqlConn = @"server=.;database=MyDataBase;Integrated security=true";//Windonws集成登录 17 18 //打开连接 19 string sqlConn = @"server=.\sqlexpress;database=MyDataBase;uid=sa;pwd=123"; 20 SqlConnection conn = new SqlConnection(sqlConn); 21 22 conn.Open(); 23 Console.WriteLine("OKS"); 24 string sts = @"create table UseLogin (id int identity(1,1) primary key,name nvarchar(10),pwd nvarchar(16) check(len(pwd) between 6 and 16))"; 25 SqlCommand cmd = new SqlCommand(sts, conn); 26 using (cmd) 27 { 28 //cmd.ExecuteNonQuery(); 29 } 30 using (conn) 31 { 32 SqlCommand cmd1 = new SqlCommand("insert into UseLogin (name,pwd) values('找2','1231234');",conn); 33 using (cmd) 34 { 35 int res = cmd1.ExecuteNonQuery(); 36 Console.WriteLine("{0}行受影响",res); 37 } 38 } 39 Console.ReadKey(); 40 } 41 } 42 }
2、查询
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace 查找 { class Program { static void Main(string[] args) { string sqlConn = @"server=.;database=MyDataBase;Integrated security=true"; string sql = @"select count(*) from uselogin where name='张三'"; using (SqlConnection conn = new SqlConnection(sqlConn)) { using (SqlCommand cmd = new SqlCommand(sql, conn)) { if (conn.State == System.Data.ConnectionState.Closed) { conn.Open(); } int res = Convert.ToInt32(cmd.ExecuteScalar()); Console.WriteLine("找到{0}个", res); } } Console.ReadKey(); } }