背景
业务需要,做一个服务启动方便,服务需要连接Sql Server数据库写数据。
问题
启动服务报错:
在OnStart方法中 WriteLog(“error:”+ex.Message);
捕获到:“error:实例失败。”;
说明创建实例对象conn时失败。那就打印WriteLog($“conn:{conn.State}”);
发现“conn:Closed”;说明数据库没有连接成功。
DapperDbContext _dapperDbContext = new DapperDbContext();
protected override void OnStart(string[] args)
{
using (var conn = _dapperDbContext.CreateConnection())
{
try
{
WriteLog($"conn:{conn.State}");
if (conn.State!=ConnectionState.Open)
{
conn.Open();
}
//业务
}
catch (Exception ex)
{
WriteLog("error:"+ex.Message);
throw;
}
}
}
数据库连接配置app.config文件:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=MyKing\\SQLEXPRESS;Initial Catalog=KingDB;User ID=sa;Password=123;" />
</appSettings>
</configuration>
解决
1、网上说不能用密码登录数据库。经测试不能解决。
2、把Data Source的值改为localhsot、. 、127.0.0.1。经测试不能解决。
3、配置修改SQL Server数据库中的:登录名、用户或角色。也不能解决。
最终经过很长的资料查询,灵光一闪,是不是服务中只能通过IP地址访问数据库呢?经刚那个测试127.0.0.1也连不上啊。
这时想起数据库的端口号1433好像需要配置一下,才能通过IP访问。
好了,怎么配置端口呢?
需要在“Sql Server 2014配置管理” 其中进行配置。如下图
配置完成,
配置文件app.config中连接修改为:
<add key="ConnectionString" value="Data Source=127.0.0.1;Initial Catalog=KingDB;User ID=sa;Password=123;" />
重启“SQL Server (SQLEXPRESS)”服务。
至此问题解决。