admin管理员组

文章数量:1794759

C#连接SQLserver数据库

C#连接SQLserver数据库

导入命名空间 using System.Configuration; using System.Data.SqlClient; using System.Data; 类

  • ConfigurationManager
  • SqlDataReader
  • SqlConnection
  • SqlCommand
结构
  • CommandBehavior
1.配置文件,在主窗体的App.config文件中添加以下Xml代码。 <connectionStrings> <add name="connString" connectionString="Data Source=PC-20210825AMUY\\WOLL;Initial Catalog=TestData;User Id=sa;Password=87352092"/> </connectionStrings>

完成后如下图

2.定义用于访问数据库的类–SQLHelper
  • 定义SQLHelper类
//定义成静态类方便使用 public static class SQLHelper { //ConfigurationManager需要引用System.configuration程序集 private static string connString = ConfigurationManager.ConnectionStrings["connString"].ToString(); //获取SQlReader public static SqlDataReader GetSqlReader(string sql)/*读取流*/ { SqlConnection sqlConn = new SqlConnection(connString); SqlCommand sqlComm = new SqlCommand(sql, sqlConn); try { sqlConn.Open(); return sqlComm.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception ex) { throw ex; } } } 3.定义利用SQLHelper获取需要的数据的类StudentServices,在此定义一个Student类作为例子
  • 定义Student类
public class Student { public int sNo { get; set; }//编号 public string Name { get; set; }//姓名 public string Birthday { get; set; }//生日 public string Gender { get; set; }//性别 public string Phone { get; set; }//手机号 public string Email { get; set; }//邮箱 public string Address { get; set; }//地址 public string StudentPic { get; set; }//学生地址 }
  • 定义StudentServices类
public static class StudentServices { //利用数据库访问通用类来获取数据表 public static List<Student> GetStudentData() { List<Student> StudentList = new List<Student>(); string sql = "select sNO, Name, Birthday, Gender, Phone, Email, Address, StudentPic from dbo.Students"; try { SqlDataReader SQLReader = SQLHelper.GetSqlReader(sql); if (!SQLReader.HasRows) return null; else { while (SQLReader.Read()) { StudentList.Add( new Student { sNo = Convert.ToInt32(SQLReader["sNo"]), Name = SQLReader["Name"].ToString(), Birthday = SQLReader["Birthday"].ToString(), Gender = SQLReader["Gender"].ToString(), Phone = SQLReader["Phone"].ToString(), Email = SQLReader["Email"].ToString(), Address = SQLReader["Address"].ToString(), StudentPic = SQLReader["StudentPic"].ToString() } ); } } return StudentList; } catch (Exception ex) { throw ex; } } } 4.使用 class Program { static List<Student> stuList; static void Main(string[] args) { stuList=StudentServices.GetStudentData(); for (int i = 0; i < stuList.Count; i++) { Console.WriteLine(stuList[i].Name); } Console.ReadKey(); } }

本文标签: 数据库sqlserver