如何在不使用Entity Framework的情况下从.Net Core连接到SQL Server?

时间:2017-05-06 21:37:03

标签: sql-server .net-core

如何在不使用Entity Framework的情况下从.Net Core连接到SQL Server?

3 个答案:

答案 0 :(得分:12)

您可以简单地使用使用SqlConnection

的传统方式

这是一个例子

 public class BaseDataAccess
 {
    protected string ConnectionString { get; set; }

    public BaseDataAccess()
    {
    }

    {
    public BaseDataAccess(string connectionString)
    private SqlConnection GetConnection()
        this.ConnectionString = connectionString;
    }

    {
        if (connection.State != ConnectionState.Open)
        SqlConnection connection = new SqlConnection(this.ConnectionString);
            connection.Open();
        return connection;
        SqlCommand command = new SqlCommand(commandText, connection as SqlConnection);
    }

    protected DbCommand GetCommand(DbConnection connection, string commandText, CommandType commandType)
    {
    protected SqlParameter GetParameter(string parameter, object value)
        command.CommandType = commandType;
        return command;
    }

    {
        parameterObject.Direction = ParameterDirection.Input;
        SqlParameter parameterObject = new SqlParameter(parameter, value != null ? value : DBNull.Value);
        return parameterObject;
    }

        SqlParameter parameterObject = new SqlParameter(parameter, type); ;
    protected SqlParameter GetParameterOut(string parameter, SqlDbType type, object value = null, ParameterDirection parameterDirection = ParameterDirection.InputOutput)
    {

        if (type == SqlDbType.NVarChar || type == SqlDbType.VarChar || type == SqlDbType.NText || type == SqlDbType.Text)
        {
    }
            parameterObject.Size = -1;
        }

        parameterObject.Direction = parameterDirection;

        if (value != null)
        {
            parameterObject.Value = value;
        }
        else
        {
            parameterObject.Value = DBNull.Value;
        }

        return parameterObject;

                DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
    protected int ExecuteNonQuery(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
    {
        int returnValue = -1;

        try
        {
            using (SqlConnection connection = this.GetConnection())
            {

                if (parameters != null && parameters.Count > 0)
                {
                    cmd.Parameters.AddRange(parameters.ToArray());
                }

            using (DbConnection connection = this.GetConnection())
                returnValue = cmd.ExecuteNonQuery();
            }
        }
        catch (Exception ex)
        {
            //LogException("Failed to ExecuteNonQuery for " + procedureName, ex, parameters);
            throw;
        }

        return returnValue;
    }

    protected object ExecuteScalar(string procedureName, List<SqlParameter> parameters)
    {
        object returnValue = null;

        try
        {
            {
        }
                DbCommand cmd = this.GetCommand(connection, procedureName, CommandType.StoredProcedure);

                if (parameters != null && parameters.Count > 0)
                {
                    cmd.Parameters.AddRange(parameters.ToArray());
                }

                returnValue = cmd.ExecuteScalar();
            }
        }
        catch (Exception ex)
        {
            //LogException("Failed to ExecuteScalar for " + procedureName, ex, parameters);
            throw;

        return returnValue;
    }

                ds = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    protected DbDataReader GetDataReader(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
    {
        DbDataReader ds;

        try
        {
            DbConnection connection = this.GetConnection();
            {
                DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
                if (parameters != null && parameters.Count > 0)
                {
                    cmd.Parameters.AddRange(parameters.ToArray());
                }

            }
        }
        catch (Exception ex)
        {
 }
            //LogException("Failed to GetDataReader for " + procedureName, ex, parameters);
            throw;
        }

        return ds;
    }

可以找到更多here

<强>更新

你必须添加nuget包

 Install-Package System.Data.SqlClient 

that is still confusing for me... .Net Core & .Net standard vs regular .Net: How do we know which packages we can use with .Net core?

依赖关系意味着你应该在你的机器上安装以便使用软件包或nuget的东西会为你安装它 要了解更多依赖关系如何在.net中查看here
注意 如果nuget包目标.net standard库主要用于.net核心和.net标准框架

答案 1 :(得分:4)

如果您对Traceback (most recent call last): File "pkl_to_csv.py", line 10, in <module> words, embeddings = pickle.load(open(fin, 'rb'), encoding='latin1') ValueError: too many values to unpack (expected 2) 类格式的另一个答案感到惊讶,并且引用的文章与我相同,那么这是格式正确的示例...希望可以为您节省一些时间

BaseDataAccess

答案 2 :(得分:0)

这是针对在Visual Studio 2019社区版中经过测试的ASP.NET MVC Core 3.1项目的解决方案。

在SQL Express中创建一个小型数据库。 然后,

在appsettings.json中添加几行作为连接字符串:

  "ConnectionStrings": {
    //PROD on some server
    "ProdConnection": "Server=somePRODServerofYours;Database=DB_xxxxx_itemsubdb;User Id=DB_xxxxx_user;Password=xxsomepwdxx;Integrated Security=false;MultipleActiveResultSets=true;encrypt=true",

    //DEV on localhost
    "DevConnection": "Server=someDEVServerofYours;Database=DB_xxxxx_itemsubdb;User Id=DB_xxxxx_user;Password=xxsomepwdxx;Integrated Security=false;MultipleActiveResultSets=true;"
  },

... 然后在您的控制器中使用类似于以下代码的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace SomeNameSpace.Controllers
{
    //This Model class should be saved somewhere else in your project.
    //It is placed here for simplicity.
    public class XtraSimpleContent
    {
        public string UserName { get; set; }
        public string References { get; set; }
        public string CreatedTime { get; set; }
    }

    public class CodeNotesController : Controller
    {
        public IConfiguration Configuration { get; }
        public string connStr = String.Empty;

        public CodeNotesController(IConfiguration configuration, IWebHostEnvironment env)
        {
            Configuration = configuration;
            if (env.IsDevelopment())
            {
                connStr = Configuration.GetConnectionString("DevConnection");
            }
            else
            {
                connStr = Configuration.GetConnectionString("ProdConnection");
            }
        }

        [HttpGet]
        public async Task<IActionResult> CodeActionMethodToConnectToSQLnetCore()
        {
            //add  using System.Data.SqlClient;
            //     using System.Data;
            //Along with the using statements, you need the system assembly reference.
            //To add assembly you can do the following.
            //   install nuget package. Right Click on Project > Manage Nuget Packages > 
            //   Search & install 'System.Data.SqlClient' and make sure it is compatible with the type of project (Core/Standard);

            List<XtraSimpleContent> aListOfItems = new List<XtraSimpleContent>();

            string commandText = @"SELECT * FROM [dbo].[ItemSubmissions] 
                                        WHERE SUBMITTEREMAIL = @SUBMITTEREMAIL 
                                        ORDER BY CreationDatetime DESC";

            using (var connection = new SqlConnection(connStr))
            {
                await connection.OpenAsync();   //vs  connection.Open();
                using (var tran = connection.BeginTransaction())
                {
                    using (var command = new SqlCommand(commandText, connection, tran))
                    {
                        try
                        {
                            command.Parameters.Add("@SUBMITTEREMAIL", SqlDbType.NVarChar);
                            command.Parameters["@SUBMITTEREMAIL"].Value = "me@someDomain.org";

                            SqlDataReader rdr = await command.ExecuteReaderAsync();  // vs also alternatives, command.ExecuteReader();  or await command.ExecuteNonQueryAsync();

                            while (rdr.Read())
                            {
                                var itemContent = new XtraSimpleContent();
                                itemContent.UserName = rdr["RCD_SUBMITTERNAME"].ToString();
                                itemContent.References = rdr["RCD_REFERENCES"].ToString();
                                itemContent.CreatedTime = rdr["CreationDatetime"].ToString();

                                aListOfItems.Add(itemContent);
                            }
                        }
                        catch (Exception Ex)
                        {
                            string msg = Ex.Message.ToString();
                            tran.Rollback();
                            throw;
                        }
                    }
                }
            }

            string totalinfo = string.Empty;
            foreach (var itm in aListOfItems)
            {
                totalinfo = totalinfo + itm.UserName + itm.References + itm.CreatedTime;
            }
            return Content(totalinfo);

        }
    }
}

使用类似以下内容进行测试: https://localhost:44302/CodeNotes/CodeActionMethodToConnectToSQLnetCore