C# 自定义MySqlHelp类,包含了获取DataTable的方法,但是调用时总是提示“类型初始值设定项引发异常”
代码:classMySqlHelper{privatestaticstringconStr=ConfigurationManager.ConnectionStrings[...
代码:
class MySqlHelper
{
private static string conStr = ConfigurationManager.ConnectionStrings["conListOfOrder"].ConnectionString;
private static MySqlConnection conn;
public static MySqlConnection Conn
{
get
{
//判断连接是否为空或者连接通道已断开
if (conn == null || conn.State == ConnectionState.Broken)
{
//重置连接通道为当前设定
conn = new MySqlConnection(conStr);
}
return conn;
}
}
public static DataTable GetDataTable(string mysqlStr, params MySqlParameter[] paras)
{
MySqlCommand cmd = new MySqlCommand(mysqlStr, Conn);
if (paras != null && paras.Length > 0)
{
cmd.Parameters.AddRange(paras);
}
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
da.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
return dt;
}
#endregion
调用:
private void LoadUsers()
{
string mysqlGetUsers = "select * from users";
DataTable dt = MySqlHelper.GetDataTable(mysqlGetUsers);
dgvUser.DataSource = dt;
}
出错位置:DataTable dt = MySqlHelper.GetDataTable(mysqlGetUsers);
错误:类型初始值设定项引发异常 展开
class MySqlHelper
{
private static string conStr = ConfigurationManager.ConnectionStrings["conListOfOrder"].ConnectionString;
private static MySqlConnection conn;
public static MySqlConnection Conn
{
get
{
//判断连接是否为空或者连接通道已断开
if (conn == null || conn.State == ConnectionState.Broken)
{
//重置连接通道为当前设定
conn = new MySqlConnection(conStr);
}
return conn;
}
}
public static DataTable GetDataTable(string mysqlStr, params MySqlParameter[] paras)
{
MySqlCommand cmd = new MySqlCommand(mysqlStr, Conn);
if (paras != null && paras.Length > 0)
{
cmd.Parameters.AddRange(paras);
}
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
da.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
return dt;
}
#endregion
调用:
private void LoadUsers()
{
string mysqlGetUsers = "select * from users";
DataTable dt = MySqlHelper.GetDataTable(mysqlGetUsers);
dgvUser.DataSource = dt;
}
出错位置:DataTable dt = MySqlHelper.GetDataTable(mysqlGetUsers);
错误:类型初始值设定项引发异常 展开
1个回答
展开全部
private static string conStr = ConfigurationManager.ConnectionStrings["conListOfOrder"].ConnectionString;
是因为上面这一行引起的,我猜是你运行的项目没有这个配置项?
是因为上面这一行引起的,我猜是你运行的项目没有这个配置项?
更多追问追答
追问
测试了下发现确实是这个东西有问题,App.config里定义成key就读不到,定义成name就说有问题,不知道怎么整了
追答
你这个MySqlHelper是不是不在你运行的项目里面啊?是在另外一个项目吧?你要在运行的项目里面也加一个App.config,里面加上这个属性才行
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询