1

下面的代码读取文本文件,对其进行格式化,显示任何错误并将数据插入 SQL Server 数据库。我以前在 Visual Basic 中编写了以下代码,现在我正在尝试重写代码 int C#,但它不起作用。

我无法将指示插入数据库的字段:我试图将没有错误的记录插入到数据库中,即使它们与其他行有错误也是如此。

这是我一个接一个地做的项目,因为我还在学习这些东西,所以请原谅我的无知。数据库部分看起来不错,所以我没有发布它,但如果需要,我可以。

文件中的类:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;

namespace ConsoleApplication1
{
    class ClsMethods
    {
        public class MemberInfo
        {
            public static string MemberPhone;
            public static string MemberName;
            public static string MemberAddr1;
            public static string MemberAddr2;
            public static string MemberCity;
            public static string MemberState;
            public static string MemberZip;
        }

        public class ErrLog
        {
            public static int RowNum;

            public static List<string> Err;
            public  ErrLog(int row)
            {
                RowNum = row;
                Err = new List<string>();
            }

            public ErrLog()
            {
                Err = new List<string>();
            }
        }
    }
}

主代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {

        public static class MainModule
        {

           static List<ClsMethods.ErrLog> ErrList;

            public static void Main()
            {
                string strFilename = null;
                FileInfo fiFile = default(FileInfo);
                StreamReader srData = default(StreamReader);
                string strRecord = "";
                List<ClsMethods.MemberInfo> MbrList = default(List<ClsMethods.MemberInfo>);
                ClsMethods.MemberInfo MbrInfo = default(ClsMethods.MemberInfo);
                int successCount = 0;
                int failedCount = 0;
                int totalCount = 0;

                ErrList = new List<ClsMethods.ErrLog>();

                strFilename = "C:\\EMP\\Member.csv";
                fiFile = new FileInfo(strFilename);
                if (fiFile.Exists)
                {
                    if (fiFile.Length > 0)
                    {
                        MbrList = new List<ClsMethods.MemberInfo>();
                        srData = new StreamReader(strFilename);
                        while (srData.Peek() > 0) 
                        {
                            try
                            {
                                strRecord = srData.ReadLine().Replace("\"", "");
                                totalCount = totalCount + 1;
                                String[] rec = strRecord.Split(",".ToCharArray());
                                if ((ValidateRow(rec, totalCount)))
                                {
                                    MbrInfo = new ClsMethods.MemberInfo();
                                    ClsMethods.MemberInfo.MemberPhone = rec[0];
                                    ClsMethods.MemberInfo.MemberName  = rec[1];
                                    ClsMethods.MemberInfo.MemberAddr1 = rec[2];
                                    ClsMethods.MemberInfo.MemberAddr2 = rec[3];
                                    ClsMethods.MemberInfo.MemberCity  = rec[4];
                                    ClsMethods.MemberInfo.MemberState = rec[5];
                                    ClsMethods.MemberInfo.MemberZip   = rec[6];
                                    MbrList.Add(MbrInfo);
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("READ: " + ex.Message);
                                srData.Close();
                                srData.Dispose();
                            }
                            Console.WriteLine(strRecord);
                        }
                        foreach (ClsMethods.MemberInfo emp in MbrList)
                        {
                            if ((ClsDatabase.InsertMemberInfo(MbrInfo)))
                            {
                                successCount = successCount + 1;
                            }
                            else
                            {
                                failedCount = failedCount + 1;
                            }
                        }
                        Console.WriteLine("Total rows: {0} ", totalCount);
                        Console.WriteLine("Records without Errors: {0} ", MbrList.Count);
                        Console.WriteLine("Records with errors: {0} ", ErrList.Count);

                        Console.WriteLine("Inserted successfully: " + successCount.ToString());
                        Console.WriteLine("Failed: " + failedCount.ToString());

                        if ((ErrList.Count > 0))
                        {
                            Console.WriteLine("If you want to display errors press D. If you want to store errors in log file press F.");
                            ConsoleKeyInfo cki = default(ConsoleKeyInfo);
                            cki = Console.ReadKey();
                            Console.WriteLine();
                            string res = "";
                            res = cki.Key.ToString(res.ToUpper());

                            if ((res == "D"))
                            {
                                DisplayErrors();
                            }
                            else if ((res == "F"))
                            {
                                WriteErrorsToFile();
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("File " + strFilename + " is empty");
                    }
                }
                else
                {
                    Console.WriteLine("File " + strFilename + " doesn't exists");
                }

                Console.WriteLine("Program End. Press any key to exit");
                Console.ReadKey();
                Environment.Exit(0);
            }
            public static void DisplayErrors()
            {
                foreach (ClsMethods.ErrLog err in ErrList)
                {
                    foreach (string errDescr in ClsMethods.ErrLog.Err)
                    {
                        Console.WriteLine("Line " + ClsMethods.ErrLog.RowNum.ToString() + ": " + errDescr);
                    }
                }
            }

            public static void WriteErrorsToFile()
            {
                string path = "C:\\Log\\log.txt";
                // Delete the file if it exists.
                if (File.Exists(path))
                {
                    File.Delete(path);
                }

                using (StreamWriter outfile = new StreamWriter(File.Create(path)))
                {
                    foreach (ClsMethods.ErrLog err in ErrList)
                    {
                        foreach (string errDescr in ClsMethods.ErrLog.Err)
                        {
                            outfile.WriteLine("Line " + ClsMethods.ErrLog.RowNum.ToString() + ": " + errDescr);
                        }
                    }
                }
            }

            public static bool ValidateRow(string[] rec, int rowIndex)
            {
                ClsMethods.ErrLog Err = new ClsMethods.ErrLog();
                if ((rec.Length != 7))
                {
                    ClsMethods.ErrLog.Err.Add("Wrong number of values in row");
                }
                else
                {
                    rec[0] = rec[0].Replace("-", "");
                    if ((string.IsNullOrEmpty(rec[0])))
                    {   
                        ClsMethods.ErrLog.Err.Add("Phone is empty");
                    }

                    if ((string.IsNullOrEmpty(rec[1])))
                    {
                        ClsMethods.ErrLog.Err.Add("Name is empty");
                    }

                    if ((string.IsNullOrEmpty(rec[2])))
                    {
                        ClsMethods.ErrLog.Err.Add("Address is empty");
                    }

                    if ((string.IsNullOrEmpty(rec[4])))
                    {
                        ClsMethods.ErrLog.Err.Add("City is empty");
                    }

                    if ((string.IsNullOrEmpty(rec[5])))
                    {
                        ClsMethods.ErrLog.Err.Add("State is empty");
                    }

                    if ((string.IsNullOrEmpty(rec[6])))
                    {
                        ClsMethods.ErrLog.Err.Add("Zip is empty");
                    }
                }
                if ((ClsMethods.ErrLog.Err.Count > 0))
                {
                    ClsMethods.ErrLog.RowNum = rowIndex;
                    ErrList.Add(Err);
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
    }
}

数据库连接和参数:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;

namespace ConsoleApplication1
{
    class ClsDatabase
    {
        public static SqlConnection GetConnection()
        {
            SqlConnection InitCnt = null;

            InitCnt = new SqlConnection();
            InitCnt.ConnectionString = "Server=MyDB;database=Example;Trusted_Connection=true;";
            try
            {
                InitCnt.Open();
            }
            catch (Exception ex)
            {
                InitCnt.Close();
                InitCnt.Dispose();
            }

            return InitCnt;
        }

        public static bool InsertMemberInfo(ClsMethods.MemberInfo MbrInfo)
        {
            SqlConnection InitCnt = default(SqlConnection);
            SqlCommand InitCmd = default(SqlCommand);

            InitCnt = GetConnection();
            if ((InitCnt != null))
            {
                InitCmd = new SqlCommand();
                InitCmd.Connection = InitCnt;
                InitCmd.CommandText = "uspInsertMemberInformation";
                InitCmd.CommandType = CommandType.StoredProcedure;

                InitCmd.Parameters.Add(new SqlParameter("@MemberPhone", SqlDbType.NVarChar, 10));
                InitCmd.Parameters["@MemberPhone"].Direction = ParameterDirection.Input;
                InitCmd.Parameters["@MemberPhone"].Value = ClsMethods.MemberInfo.MemberPhone;

                InitCmd.Parameters.Add(new SqlParameter("@MemberName", SqlDbType.NVarChar, 50));
                InitCmd.Parameters["@MemberName"].Value = ClsMethods.MemberInfo.MemberName;
                InitCmd.Parameters["@MemberName"].Value = ClsMethods.MemberInfo.MemberName;

                InitCmd.Parameters.Add(new SqlParameter("@MemberAddr1", SqlDbType.NVarChar, 30));
                InitCmd.Parameters["@MemberAddr1"].Direction = ParameterDirection.Input;
                InitCmd.Parameters["@MemberAddr1"].Value = ClsMethods.MemberInfo.MemberAddr1;

                InitCmd.Parameters.Add(new SqlParameter("@MemberAddr2", SqlDbType.NVarChar, 30));
                InitCmd.Parameters["@MemberAddr2"].Direction = ParameterDirection.Input;
                InitCmd.Parameters["@MemberAddr2"].Value = ClsMethods.MemberInfo.MemberAddr2;

                InitCmd.Parameters.Add(new SqlParameter("@MemberCity", SqlDbType.NVarChar, 20));
                InitCmd.Parameters["@MemberCity"].Direction = ParameterDirection.Input;
                InitCmd.Parameters["@MemberCity"].Value = ClsMethods.MemberInfo.MemberCity;

                InitCmd.Parameters.Add(new SqlParameter("@MemberState", SqlDbType.NChar, 2));
                InitCmd.Parameters["@MemberState"].Direction = ParameterDirection.Input;
                InitCmd.Parameters["@MemberState"].Value = ClsMethods.MemberInfo.MemberState;

                InitCmd.Parameters.Add(new SqlParameter("@MemberZip", SqlDbType.NVarChar, 9));
                InitCmd.Parameters["@MemberZip"].Direction = ParameterDirection.Input;
                InitCmd.Parameters["@MemberZip"].Value = ClsMethods.MemberInfo.MemberZip;

                try

                {
                    InitCmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    return false;
                }
                finally
                {
                    InitCmd.Parameters.Clear();
                    InitCnt.Close();
                }
            }
            return true;
        }
    }
}
4

1 回答 1

2

那里有一些非常奇特的东西:

  • ClsMethods仅包含类且未使用;去掉它。
  • MemberInfo仅包含static字段,因此每个实例必须始终包含相同的数据。
  • ErrLog仅包含一个静态字段,因此,每个实例将始终包含相同的数据。
  • Main毫无意义地将一堆变量设置为default,这总是null,这是多余的。你为什么这样做?
  • MainModule也是多余的,应该删除。
  • 所有变量都是全局的,这是不必要且有风险的。
  • MbrInfo = new ClsMethods.MemberInfo();没用,因为所有字段都是static,您只会覆盖已经存在的内容。
  • ClsDatabase.InsertMemberInfo(MbrInfo)将始终传递最后一条记录的次数与文件中记录的次数一样多。我猜你ClsDatabase.InsertMemberInfo(emp)想要 看看为什么全局变量不好?
  • InsertMemberInfo忽略您传递的参数并为每个参数使用单个静态值。
  • 默认SqlParameter.DirectionInput,您不必重置它。

我不会在每个字段的前面添加“成员”;它已经在类名中。我猜你想要的是:

public class MemberInfo
{
    public string Phone;
    public string Name;
    public string Addr1;
    public string Addr2;
    public string City;
    public string State;
    public string Zip;
}

然后Main你可以打电话:

MemberInfo mi = new MemberInfo();
mi.Phone = rec[0];
mi.Name = rec[1];
mi.Addr1 = rec[2];
mi.Addr2 = rec[3];
mi.City = rec[4];
mi.State = rec[5];
mi.Zip = rec[6];
MbrList.Add(mi);

您使用这个词Err来指代类、日志和实例变量。这非常令人困惑。我建议类似:

public class ErrLog
{
    public int RowNum;
    public List<string> Messages;

    public ErrLog(int row)
        : base()
    {
        RowNum = row;
    }

    public ErrLog()
    {
        Messages = new List<string>();
    }
}

InsertMemberInfo应该看起来更像这样:

var sp = new SqlParameter("@MemberPhone", SqlDbType.NVarChar, 10);
sp.Value = MbrInfo.whatever;
InitCmd.Parameters.Add(sp);

不要这样做:

try
{
    InitCmd.ExecuteNonQuery();
}
 catch (Exception ex)
{
    return false;
}

这将丢弃程序失败的原因。只需这样做:

InitCmd.ExecuteNonQuery();

例外。使用它们。您的代码中还有一些奇怪的东西;从我展示的开始。

于 2012-12-19T04:02:26.943 回答