C# 连接sqlServer数据库

连接sqlServer数据库

一.创建数据库

在用[Microsoft SQL Server Management Studio]工具,建立一个数据库,然后执行下面脚本

CREATE TABLE [dbo].[Company](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](500) NULL,
    [CreateTime] [datetime] NOT NULL,
    [CreatorId] [int] NOT NULL,
    [LastModifierId] [int] NULL,
    [LastModifyTime] [datetime] NULL,
 CONSTRAINT [PK_Company] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
                                                                                                                                                        
                                                                                                                                                        
INSERT INTO [dbo].[Company]
           ([Name]
           ,[CreateTime]
           ,[CreatorId]
           ,[LastModifierId]
           ,[LastModifyTime])
     VALUES
           ('腾讯'
           ,'2020-05-26'
           ,1
           ,1
           ,'2020-05-26')
    二.

二.设置App.config中的连接字符串,如下

Data Source=服务器名;Database=数据库名;User ID=用户名;Password=密码,这些参数需要根据自己的情况,重新设置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <connectionStrings>
    <add name="DBConnect" connectionString="Data Source=localhost;Database=Text_DB;User ID=sa;Password=123"/>
  </connectionStrings>
</configuration>

三,执行下面的代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Data.SqlClient;
 7 using System.Configuration;
 8 using Ruanmou.Model;
 9 using System.Reflection;
10 
11 namespace _001_Text
12 {
13     class Program
14     {
15         /// <summary>
16         /// 从App.config中获取连接数据库字符串
17         /// </summary>
18         private static string SqlServerConnString = ConfigurationManager.ConnectionStrings["DBConnect"].ConnectionString;
19         static void Main(string[] args)
20         {
21             Company commpany = Find<Company>(1);
22             Console.WriteLine(commpany.Name);
23             Console.WriteLine(commpany.CreateTime);
24             Console.WriteLine(commpany.CreatorId);
25             Console.ReadKey();
26         }
27         public static T Find<T>(int id)
28         {
29             Type type = typeof(T);
30             string columnString = string.Join(",", type.GetProperties().Select(p => $"[{p.GetColumnName()}]"));
31             string sql = $"SELECT {columnString} FROM [{type.Name}]";
32             T t = (T)Activator.CreateInstance(type);
33             using (SqlConnection conn = new SqlConnection(SqlServerConnString))
34             {
35                 SqlCommand command = new SqlCommand(sql, conn);
36                 conn.Open();
37                 SqlDataReader reader = command.ExecuteReader();
38                 while (reader.Read())
39                 {
40                     foreach (var prop in type.GetProperties())
41                     {
42                         prop.SetValue(t, reader[prop.Name] is DBNull ? null : reader[prop.Name]);
43                     }
44                 }
45             }
46             return t;
47         }
48     }
49 
50     /// <summary>
51     /// 扩展方法,静态类,静态字段,this这几个特征组成的
52     /// </summary>
53     public static class AttributeHelper
54     {
55         public static string GetColumnName(this PropertyInfo prop)
56         {
57             if (prop.IsDefined(typeof(ColumnAttribute), true))
58             {
59                 ColumnAttribute columnName = (ColumnAttribute)prop.GetCustomAttribute(typeof(ColumnAttribute), true);
60                 return columnName.GetColumnName();
61             }
62             else
63             {
64                 return prop.Name;
65             }
66         }
67     }
68 
69     /// <summary>
70     /// 反射类
71     /// </summary>
72     [AttributeUsage(AttributeTargets.Property)]//表示此反射类只能修饰属性
73     public class ColumnAttribute : Attribute
74     {
75         private string _ColumnName = string.Empty;
76         public ColumnAttribute(string name)
77         {
78             this._ColumnName = name;
79         }
80         public string GetColumnName()
81         {
82             return _ColumnName;
83         }
84     }
85 }

执行结果如下图

 

四,知识补充

连接数据,主要用到了3个类

1>数据库连接类:SqlConnetion

位于System.Data.SqlClient的命名空间下

2>数据库命令类:SqlCommand

主要执行对数据库的操作,比如插入、删除、修改等

3>数据库读取类:SqlDataReader

是SqlCommand执行了查询操作后,返回的数据类型

其中,三个比较常用的方法

ExecuteNonQuery():提交无查询结果的SQL语句,如UPDATE,INSERT,DELETE等语句,其返回值为数据库中被SQL语句影响的行数;
ExecuteReader():提交SELECT语句,返回值是一个数据流,里面是SELECT语句的查询结果,可以用SqlDataReader对象来接收,然后调用其Read()方法来逐行读出查询结果;
ExexuteScalar():提交SELECT语句,但是其返回值是查询结果的第一行第一列,所以适用于例如COUNT等聚合查询。

 

猜你喜欢

转载自www.cnblogs.com/dfcq/p/12966747.html
今日推荐