zoukankan      html  css  js  c++  java
  • asp.net core连接sqlserver

    开发环境:win7,vs2017,sqlserver2014

    vs上建立一个asp.net core web项目和一个.net core的类库项目DBA

    简单起见,在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.NET

    重点在于如何在web项目中去调用DBA项目来实现数据库的访问

    首先肯定是要添加DBA项目的引用。

    然后在web项目的Startup类的ConfigureServices函数中添加代码:

    注意这里的数据库连接字符串,里面没有用户名和密码,就这样就可以了

    然后在控制器中通过构造函数来获取SqlServerManager的对象

     好了,这样就可以访问数据库了,只是一个简单的例子,看看就好

  • 相关阅读:
    一、Javadoc文档标记
    0-写在java系列文章之前
    Tomcat全攻略
    linux使用普通账户时,无法登录,提示“-bash: fork: retry: Resource temporarily unavailable”
    在Linux下安装和使用MySQL
    linux下修改jdk环境变量的方法
    linux下卸载系统自带或者非自带的jdk
    linux中 /etc/profile的作用
    每天一个linux命令:tar命令-jia2
    如何使用蓝湖设计稿同时适配PC及移动端
  • 原文地址:https://www.cnblogs.com/jin-/p/10387208.html
Copyright © 2011-2022 走看看