gpt4 book ai didi

c# - Asp.net MVC SQL Server 连接返回空

转载 作者:太空宇宙 更新时间:2023-11-03 20:56:52 25 4
gpt4 key购买 nike

我正在尝试连接到本地主机上的 Microsoft SQL Server。我的代码如下。

public SqlConnection con;

// To Handle connection related activities
private void connection()
{
string constr = ConfigurationManager.ConnectionStrings["Data Source = MACHINE-VOIV7EH\\SQLEXPRESS; Initial Catalog = geolog; Persist Security Info = False; "].ToString();
con = new SqlConnection(constr);
}

public List<Bob> GetAllBobs()
{
try
{
connection();
con.Open();

IList<Bob> EmpList = SqlMapper.Query<Bob>(con, "GetBobs").ToList();
con.Close();

return EmpList.ToList();
}
catch (Exception)
{
throw;
}
}

con返回null

SQL 服务器设置:

enter image description here

来自 Pyton 的配置(尝试,但另一个数据库):

conn = pypyodbc.connect('DRIVER={SQL Server};'
r'SERVER=MACHINE-VOIV7EH\SQLEXPRESS;'
r'DATABASE=vibori;'
r' autocommit=True'
)

最佳答案

问题出在您的连接字符串上。您应该从 web.config 文件中引用您的连接字符串。

Web.Config

<connectionStrings>
<add name="master" providerName="System.Data.SqlClient" connectionString="Data Source=ACHINE-VOIV7EH\\SQLEXPRESS;Initial Catalog=geolog;Integrated Security=False;User Id=your_user_id;Password=xxxxxx;MultipleActiveResultSets=True" />
</connectionStrings>

C# 文件

 SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["master"].ConnectionString);

或者你可以发送一个连接字符串如下

private void connection()
{
string constr = "Data Source=MACHINE-VOIV7EH\\SQLEXPRESS; Initial Catalog = geolog; Persist Security Info = False;";
con = new SqlConnection(constr);
}

关于c# - Asp.net MVC SQL Server 连接返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49617396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com