又是配置文件问题,真心找不到错误,求帮忙!感激不尽,这个问题困扰我好久了!
一:
.config 文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="
MyConnect" connectionString="Data Source=.\SQLEXPRESS;
AttachDBFilename=|DataDirectory|\
Test.mdf;
Integrated Security=True;User Instance=True"/>
</connectionStrings>
</configuration>
二:
Helper 类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
namespace Test
{
class Helper
{
//这里定义静态方法,通过配置文件连接SQL,执行ExecuteNonQuery.
public static int ExecuteNonQuery(string Command, params SqlParameter[] sqlParameters)
{
//通过配置文件连接SQL.
//
总是这句报错,
Object reference not set to an instance of an object.
string conStr = ConfigurationManager.ConnectionStrings["MyConnect"].ConnectionString;
using (SqlConnection connect = new SqlConnection(conStr))
{
connect.Open();
using (SqlCommand cmd = connect.CreateCommand())
{
cmd.CommandText = Command; //sql语句命令.
foreach (SqlParameter sqlParameter in sqlParameters)
{
cmd.Parameters.Add(sqlParameter); //sql语句需的参数.
}
return cmd.ExecuteNonQuery();
}
}
}
}
}
三:
带执行的类:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
u