我一直收到错误
connectionstring属性尚未初始化
我正在寻找一个小时,我试图将解决方案应用于我的项目但是,它没有用
我将错误日志插入sql表
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace ErrorLog
{
internal class LogToDB : ILog
{
static string connection_string = ConfigurationSettings.AppSettings["Sever"];
public void logNow(string strError)
{
SqlConnection conn = new SqlConnection(connection_string);
List<string> errors = new List<string>();
try
{
string strSQL = "insert_errolog";
SqlDataAdapter mySA = new SqlDataAdapter(strSQL, conn);
mySA.SelectCommand.CommandType = CommandType.StoredProcedure;
mySA.SelectCommand.Parameters.Add(new SqlParameter("@errorMsg", SqlDbType.VarChar, 50));
mySA.SelectCommand.Parameters["@errorMsg"].Value = strError;
DataSet myDS = new DataSet();
mySA.Fill(myDS);
}
catch (Exception e)
{
errors.Add("Error: " + e.ToString());
}
finally
{
conn.Dispose();
conn = null;
}
}
}
}
这是App.config
文件
<configuration>
<appSettings>
<add key="Destination" value="ToSQL"/>
<add key="Sever" value="Data Source=MYSQLSEVER ;Initial Catalog=Myproject;User Id=test1;Password=12345"/>
</appSettings>
</configuration>
当我插入数据时,它抛出异常:
connectionstring属性尚未初始化
有没有人在我的代码中看到问题?
答案 0 :(得分:0)
您可以像这样使用连接字符串(在app.config中):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
</connectionStrings>
</configuration>
答案 1 :(得分:0)
您没有打开连接。
conn.Open();
答案 2 :(得分:0)
尝试对您的连接字符串进行编码,以确认其是否正常
用此替换此行 static string connection_string = ConfigurationSettings.AppSettings [“Sever”];
static string connection_string = "Data Source=MYSQLSEVER ;Initial Catalog=Myproject;User Id=test1;Password=12345";
看看是否有效,如果有效,则不会正确地从appsettings获取连接字符串值。
答案 3 :(得分:0)
Net Developer,
您可以转换c#
中的代码你应该这样做
制作全局连接变量
dim con as new SQLConnection
con.connectionsting = "Set your connection string"
con.open
'after when you write what your code then write
con.close
它将解决您的连接属性未初始化问题
希望它有所帮助。答案 4 :(得分:-1)
在这行代码中static string connection_string = ConfigurationSettings.AppSettings["Sever"];
你应该写“connectionstring
”而不是“Server
”。