zoukankan      html  css  js  c++  java
  • DataBase 学习笔记一:c#连接SQL数据库

    1、创建一个静态方法类SQLDataBaseConnection

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using System.Data;
    using System.Data.Odbc;
    using System.Data.SqlClient;
    
    namespace ExcelApplication
    {
        public static class SQLDataBaseConnection
        {
            private const string connectionString = "Data Source=WIN-MQICJPHBJ43\SQLEXPRESS;Initial Catalog=Application;Persist Security Info=True;User ID=sa;Password=123456";
    
            public static List<Dictionary<string, string>> GetSQLConnection(string sql)
            {
                SqlConnection con = new SqlConnection(connectionString);
    
                con.Open();
    
                SqlCommand command = new SqlCommand(sql, con);
    
                SqlDataReader reader = command.ExecuteReader();
    
                List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
    
                while (reader.Read())
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    for (var i = 0; i < reader.FieldCount; i++)
                    {
                        dic.Add(reader.GetName(i).ToString(), reader.GetValue(i).ToString());
                    }
                    list.Add(dic);
                }
    
                reader.Close();
    
                con.Close();
    
                return list;
            }
        }
    }

    2.在需要使用的地方直接调用

     string sql = "select * from CM_Users";
     var a = SQLDataBaseConnection.GetSQLConnection(sql);
  • 相关阅读:
    软件包的作用
    Sqlserver2008 表分区教程
    C#通用类型转换 Convert.ChangeType
    缓存 HttpContext.Current.Cache和HttpRuntime.Cache的区别
    用户信息 Froms验证票证
    .NET4.0 __doPostBack未定义
    TFS2012 安装 配置笔记
    MVC学习笔记一
    新博客..第一天..
    ORACLE多表查询优化
  • 原文地址:https://www.cnblogs.com/workformylove/p/3665166.html
Copyright © 2011-2022 走看看