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);

 

posted on 2014-04-14 22:55  不死小强  阅读(252)  评论(0编辑  收藏  举报

导航