asp.net core鏈接sqlserver

開發環境:win7,vs2017,sqlserver2014web

vs上創建一個asp.net core web項目和一個.net core的類庫項目DBAsql

簡單起見,在DBA項目中就一個類SqlServerManager:數據庫

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;

namespace DBA
{
    public class SqlServerManager : DbContext
    {
        private IDbConnection connection = null;
        private SqlCommand command = null;
        public SqlServerManager(DbContextOptions<SqlServerManager> options) : base(options) {
            if(null== connection)
                connection = Database.GetDbConnection();//這個GetDbConnection須要在NuGet中添加Microsoft.AspNetCore.App

            if (connection.State == ConnectionState.Closed)
                connection.Open();
            if (command == null)
                command=connection.CreateCommand() as SqlCommand;

        }

        

        public int Insert<T>(T table)
        {
            try { 
            command.CommandText = GetInsertSqlStr(table, command.Parameters);
            return command.ExecuteNonQuery();}
            catch(Exception ex)
            {
                throw ex;
            }
        }
        public void ExecSqlStr(string sql,Dictionary<string,object> Parameters)
        {
            command.CommandText = sql;
            foreach(var str in Parameters.Keys)
            {
                var value = Parameters.GetValueOrDefault(str);
                command.Parameters.Add(
                    new SqlParameter()
                    {
                        ParameterName="@"+str,
                        Value= value,
                        DbType= GetDbType(value.GetType())
                    }
                    );
            }
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = command;
            DataSet myDataSet = new DataSet();
            da.Fill(myDataSet);
            DataTable db = myDataSet.Tables[0];
        }


        private string GetInsertSqlStr<T>(T table,SqlParameterCollection sqlParameters)
        {
            string strSql = "insert into "+ typeof(T).Name + " (";
            //得到泛型類型的公共屬性
            var pros = typeof(T).GetProperties().Where(pi => !Attribute.IsDefined(pi, typeof(NotMappedAttribute))).ToArray();
            string values = "";
            foreach (PropertyInfo p in pros)
            {
                strSql += p.Name + ",";
                values += "@" + p.Name + ",";

                sqlParameters.Add(new SqlParameter() {
                    ParameterName = "@" + p.Name,
                    Value = p.GetValue(table),
                    DbType = GetDbType(p.PropertyType)
                });
            }
            values = values.Substring(0, values.Length - 1);
            strSql = strSql.Substring(0, strSql.Length - 1) + ") values ("+ values+")";
            return strSql;
        }

        private DbType GetDbType(Type t)
        {
            switch (Type.GetTypeCode(t))
            {
                case TypeCode.Boolean:
                    return DbType.Boolean;
                case TypeCode.Byte:
                    return DbType.Byte;
                case TypeCode.DateTime:
                    return DbType.DateTime;
                case TypeCode.Decimal:
                    return DbType.Decimal;
                case TypeCode.Double:
                    return DbType.Double;
                case TypeCode.Int16:
                    return DbType.Int16;
                case TypeCode.Int32:
                    return DbType.Int32;
                case TypeCode.Int64:
                    return DbType.Int64;              
                case TypeCode.String:
                    return DbType.String;
                default:
                    return DbType.Object;
            }
        }
    }
}

本文的重點不在於DBA項目中如何去訪問數據庫,這裏能夠用EF,也能夠用ADO.NET等等,我這裏用的是ADO.NETapp

重點在於如何在web項目中去調用DBA項目來實現數據庫的訪問asp.net

首先確定是要添加DBA項目的引用。函數

而後在web項目的Startup類的ConfigureServices函數中添加代碼:sqlserver

注意這裏的數據庫鏈接字符串,裏面沒有用戶名和密碼,就這樣就能夠了spa

而後在控制器中經過構造函數來獲取SqlServerManager的對象.net

 

 好了,這樣就能夠訪問數據庫了,只是一個簡單的例子,看看就好code

相關文章
相關標籤/搜索