简体   繁体   English

将文本文件数据插入到特定列的SQL Server数据库表中

[英]Insert text file data into SQL Server database table of specific column

I have attached my code in which I tried to read a .txt file with many records. 我已经附加了我的代码,其中我尝试读取包含许多记录的.txt文件。

The same text file data I need to insert into the SQL Server database table in specific columns. 我需要在特定列的SQL Server数据库表中插入相同的文本文件数据。 Here is the code I wrote by taking reference from some where. 这是我通过引用某些地方编写的代码。

protected void BtnUpload_Click(object sender, EventArgs e)
{
    FileUpload(x);
}

private void FileUpload(List<string> x)
{       
    SqlConnection con = new SqlConnection(conStr);
    SqlCommand cmd = new SqlCommand();

    string fileName = Path.Combine(@"C:\Users\user\Desktop\SBS", FileUpload1.FileName);        

    if(FileUpload1.HasFile)
    {
        try
        {
            con.Open();
            List<string> x;

            for (int i = 0; i <= x.Count - 9; i += 9)
            {
                SqlCommand myCommand = new SqlCommand("INSERT INTO SBSFile (SBSBranchCode, BranchName, FinYear, BrChallanNo, TransDate, MajorHead, ReceiptPayment, Amount, PlanNonPlan) " +
                           string.Format("Values('{0}', '{1}',  '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}')", x[i], x[i + 1], x[i + 2], x[i + 3], x[i + 4], x[i + 5], x[i + 6], x[i + 7], x[i + 8], x[i + 9]), con);
                myCommand.ExecuteNonQuery();
         }
         catch (Exception ex)
         {
         }
     }
 }

example of my file : 我的文件示例:

1 |abc| 1 | abc | |bcd| | bcd | |101| | 101 |

here | 这里| denoted separator of column and yes every line should be inserted in the table where in specific column is available 表示为列的分隔符,是的,应将每行插入表格中的特定列中

Can anyone help me to insert file data into the SQL Server table? 谁能帮我将文件数据插入SQL Server表中?

Please help me to solve the issue 请帮我解决问题

I wouldn't use a program at all... I'd use the "Import" feature in SQL server to import a pipe-delimited file. 我根本不会使用程序...我会使用SQL Server中的“导入”功能来导入管道分隔文件。 For example How to import pipe delimited text file data to SQLServer table 例如如何将管道分隔的文本文件数据导入SQLServer表

Here is an example of working code that will read data from a Text file, where that data is delimited by | 这是一个工作代码示例,该代码将从Text文件读取数据,其中该数据由|分隔| . Multiple insert statements will be executed within a single transaction, in case of failure using an All Or Nothing principle. 如果使用全有或全无原则失败,则将在单个事务中执行多个插入语句。

[TestMethod]
public void TestInsertDataFromFile()
{
    String fileName = @"D:\SampleData.txt";
    String connectionString = @"Server=MyTestDBServer; Database=TestingDatabase; Trusted_Connection=True;";
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();

        using (SqlTransaction transaction = conn.BeginTransaction())
        {
            String insertCommand = @"INSERT INTO SBSFile (SBSBranchCode, BranchName, FinYear, BrChallanNo, TransDate, MajorHead, ReceiptPayment, Amount, PlanNonPlan) ";
            insertCommand += @"VALUES (@sbsBranchCode, @branchName, @finYear, @brChallanNo, @transDate, @majorHead, @receiptPayment, @amount, @planNonPlan)";

            String[] fileContent = File.ReadAllLines(fileName);

            using (SqlCommand command = conn.CreateCommand())
            {
                command.CommandText = insertCommand;
                command.CommandType = CommandType.Text;
                command.Transaction = transaction;

                foreach (String dataLine in fileContent)
                {
                    String[] columns = dataLine.Split('|');
                    command.Parameters.Clear();

                    command.Parameters.Add("sbsBranchCode", SqlDbType.VarChar).Value = columns[0];
                    command.Parameters.Add("branchName", SqlDbType.VarChar).Value = columns[1];
                    command.Parameters.Add("finYear", SqlDbType.VarChar).Value = columns[2];
                    command.Parameters.Add("brChallanNo", SqlDbType.VarChar).Value = columns[3];
                    command.Parameters.Add("transDate", SqlDbType.VarChar).Value = columns[4];
                    command.Parameters.Add("majorHead", SqlDbType.VarChar).Value = columns[5];
                    command.Parameters.Add("receiptPayment", SqlDbType.VarChar).Value = columns[6];
                    command.Parameters.Add("amount", SqlDbType.VarChar).Value = columns[7];
                    command.Parameters.Add("planNonPlan", SqlDbType.VarChar).Value = columns[8];

                    command.ExecuteNonQuery();
                }
            }

            transaction.Commit();
        }
    }
}

Important things to note 重要注意事项

  1. NEVER have an empty catch {} handler as you will never know if there are problems. 永远不要有一个空的catch {}处理函数,因为您永远不会知道是否存在问题。
  2. When talking to the database using externally specified values, ALWAYS use parameters to prevent SQL Injection attacks. 当使用外部指定的值与数据库对话时,始终使用参数来防止SQL注入攻击。
  3. Make use of Transactions if you are doing multiple inserts from a single source. 如果您要从一个来源进行多次插入,请使用事务。 It will make recovery possible without having to unpick the data manually. 这将使恢复成为可能,而无需手动取消选择数据。
  4. Where possible (when classes implement IDisposable ) use a using(...) block to ensure resources are released and not blocking/locking. 在可能的情况下(当类实现IDisposable时 )使用using(...)块来确保释放资源,而不是阻塞/锁定。

use this code: 使用此代码:

        SqlConnection con = new SqlConnection(conStr);
        SqlCommand cmd = new SqlCommand();

        string fileName = Path.Combine(@"C:\Users\user\Desktop\SBS", FileUpload1.FileName);

        if (FileUpload1.HasFile)
        {
            var lines = File.ReadAllLines(fileName);
            try
            {
                con.Open();

                foreach (var line in lines)
                {
                    var columns = line.Split('|');
                    SqlCommand myCommand = new SqlCommand("INSERT INTO SBSFile (SBSBranchCode, BranchName, FinYear, BrChallanNo, TransDate, MajorHead, ReceiptPayment, Amount, PlanNonPlan) " +
                               $"Values('{columns[0]}', '{columns[1]}','{columns[2]}','{columns[3]}','{columns[4]}','{columns[5]}','{columns[6]}','{columns[7]}','{columns[8]}''{columns[9]}')");
                    myCommand.ExecuteNonQuery();
                }
                con.Close();
            }
            catch (Exception ex)
            {
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM