使用c#代码实现对数据库批量新增

71 阅读1分钟
using System;
using System.Data;
using System.Data.SqlClient;

namespace DatabaseBatchInsert
{
    class Program
    {
        static void Main(string[] args)
        {
            // Connection string for your database
            string connectionString = "Data Source=yourserver;Initial Catalog=yourdatabase;Integrated Security=True";

            // Create a new SqlConnection object
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                // Open the connection
                connection.Open();

                // Start a new transaction
                using (SqlTransaction transaction = connection.BeginTransaction())
                {
                    try
                    {
                        // Create a new SqlCommand object
                        using (SqlCommand cmd = new SqlCommand("INSERT INTO yourtable (col1, col2, col3) VALUES (@col1, @col2, @col3)", connection, transaction))
                        {
                            // Add the parameters
                            cmd.Parameters.Add("@col1", SqlDbType.Int);
                            cmd.Parameters.Add("@col2", SqlDbType.VarChar, 50);
                            cmd.Parameters.Add("@col3", SqlDbType.DateTime);

                            // Loop through the list of data and insert each row
                            foreach (var data in yourListOfData)
                            {
                                cmd.Parameters["@col1"].Value = data.Col1;
                                cmd.Parameters["@col2"].Value = data.Col2;
                                cmd.Parameters["@col3"].Value = data.Col3;

                                cmd.ExecuteNonQuery();
                            }
                        }

                        // Commit the transaction
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        // Rollback the transaction on error
                        transaction.Rollback();

                        // Log the error message
                        Console.WriteLine("Error: " + ex.Message);
                    }
                }
            }
        }
    }
}