对象引用未设置为对象错误的实例

时间:2018-09-28 03:26:06

标签: c# mysql

我已经编写了Windows服务,以使用C#将CSV数据插入MySQL数据库表中。

我已经使用Answer 1作为插入方法的参考。

在“连接字符串”行中,出现错误:

  

System.NullReferenceException HResult = 0x80004003消息=对象   引用未设置为对象的实例。

     

System.Configuration.ConnectionStringSettingsCollection.this [string] .get   返回null。

插入的源代码:

        public  void insert()
        {
const string CSV_CONNECTIONSTRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"{0}\";Extended Properties=\"text;HDR=YES;FMT=Delimited\"";
string CSVpath = @"C:\Users\Admin\source\";  // CSV file Path you can use file choose control
var AllFiles = new DirectoryInfo(CSVpath).GetFiles("*.CSV");
string File_Name = string.Empty;
**string ConStr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString; //error line


for (int i = 0; i < AllFiles.Length; i++)
{
    try
    {
        File_Name = AllFiles[i].Name;
        DataTable dt = new DataTable();
        using (OleDbConnection con = new OleDbConnection(string.Format(CSV_CONNECTIONSTRING, CSVpath)))
        {
            using (OleDbDataAdapter da = new OleDbDataAdapter("select * from [" + File_Name + "]", con))
            {
                da.Fill(dt);
            }
        }
        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(ConStr))
        {
            bulkCopy.ColumnMappings.Add(0, "Column1");
            bulkCopy.ColumnMappings.Add(1, "Column2");
            bulkCopy.ColumnMappings.Add(2, "Column3");
            bulkCopy.DestinationTableName = "myTable";
            bulkCopy.BatchSize = dt.Rows.Count;
            bulkCopy.WriteToServer(dt);
            bulkCopy.Close();
        }                   
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
}

App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <system.data>
    <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
      <add description=".Net Framework Data Provider for MySQL" invariant="MySql.Data.MySqlClient" name="MySQL Data Provider" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.10.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.10.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
      </provider></providers>
  </entityFramework>
</configuration>

关于MySQL表信息还有一个问题。我找不到要写入数据的MySQL表行。

2 个答案:

答案 0 :(得分:1)

我敢打赌,string ConStr = ConfigurationManager.ConnectionStrings["ConStr"]结果为空。

您可以:

  1. string ConStr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString拆分为

    var setting = ConfigurationManager.ConnectionStrings["ConStr"];
    if( setting == null ) {
          throw new Exception ("Unable to retrieve connection string")
    }
    string ConStr = setting.ConnectionString;
    if( string.IsNullOrEmpty(ConStr) ) {
          throw new Exception ("Connection string is empty");
    }
    
  2. 在'var setting ='之后的第一行放置一个断点,并检查该值。


编辑

编辑后,我可以看到您在配置中缺少connectionstrings部分。可能是这样的:

<connectionStrings> <add name="ProductDBConnection" connectionString="Server=tcp:(...);Connection Timeout=30" providerName="System.Data.SqlClient" /> </connectionStrings>

(此为MS Sql Server,您需要为MySql找到一个)

答案 1 :(得分:1)

您错过了app.config中的连接字符串。将其添加到您的app.config。

例如:

<connectionStrings>
    <add name="ConStr" connectionString="Server=127.0.0.1; Database=databaseName;Uid=yourUserName;Pwd='Yourpasword'" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>