admin管理员组

文章数量:1794759

VS2010使用c#连接SQLServer数据库

VS2010使用c#连接SQLServer数据库

准备工作: 准备好vs2010,SQLServer2008的安装包,如果需要的话,留下邮箱我发给你

第一步:安装VS2010

 

 

 

 

 

 

 

 

 

 

  

第二步:安装SQLServer2008

 

 

 

 

注:这里也可以选择默认实例 

 

 

 

 

 

第三步:使用c#连接SQLServer数据库

 

使用SQLServer的管理工具登录数据库,选择sql server身份验证,用户名填写sa 密码是刚才安装过程中输入的密码

新建一个数据库,这里我新建了一个mysql数据库,然后新建一个表student

 

                                                       表的结构如下,有姓名sname, 学号 sno, 性别 sex , 年龄 age

                                                         右键表,编辑前200行,输入数据

                                             新建一个查询,查看数据是否写入成功

use mysql select sname ,sno,sex,age from student

                                             点击执行,结果如下:

 

使用c#连接数据库,新建一个c#控制台应用程序

using System; using System.Data; using System.Data.SqlClient; using System.Collections.Generic; using System.Linq; using System.Text; namespace 连接数据库 { class Program { static void Main(string[] args) { //指定Sql Server提供者的连接字符串 string connString = "server=WIN-JUKODHILVDP\\\\SQLEXPRESS;database =mysql;uid=sa;pwd=123456"; //建立连接对象 SqlConnection Sqlconn = new SqlConnection(connString); //打开连接 Sqlconn.Open(); //为上面的连接指定Command对象 SqlCommand thiscommand = Sqlconn.CreateCommand(); thiscommand.CommandText = "select sname,sno,sex,age from student"; //为指定的command对象执行DataReader SqlDataReader thisSqlDataReader = thiscommand.ExecuteReader(); while (thisSqlDataReader.Read()) { Console.WriteLine("{0} {1} {2} {3}", thisSqlDataReader["sname"], thisSqlDataReader["sno"], thisSqlDataReader["sex"], thisSqlDataReader["age"]); } //关闭读取 thisSqlDataReader.Close(); //关闭连接 Sqlconn.Close(); Console.ReadLine(); } } }

 

注意:服务器名 sever有\\的话,要使用转义字符\\\\

 

运行结果如下:

总结:1.建立与数据库的连接 

          2.查询数据

          3.关闭连接

本文标签: 数据库sqlserver