Here’s an example code in C# using the .NET framework to write data from a CSV file to a SQL database
using System; using System.Data.SqlClient; using System.IO; namespace CsvToSqlServerExample { class Program { static void Main(string[] args) { // Define the connection string for the SQL Server database string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MyDatabase;Integrated Security=True"; // Define the path to the CSV file string csvFilePath = "customers.csv"; // Define the SQL statement to create a table in the SQL Server database string createTableSql = "CREATE TABLE IF NOT EXISTS Customers (FirstName VARCHAR(50), LastName VARCHAR(50), Email VARCHAR(50))"; // Execute the SQL statement to create the table in the SQL Server database using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand(createTableSql, connection)) { command.ExecuteNonQuery(); } } // Read the data from the CSV file and insert it into the SQL Server database using (StreamReader reader = new StreamReader(csvFilePath)) { string line; // Loop through the lines of data in the CSV file while ((line = reader.ReadLine()) != null) { string[] fields = line.Split(','); // Define the SQL statement to insert data into the SQL Server database string insertSql = "INSERT INTO Customers (FirstName, LastName, Email) VALUES ('" + fields[0] + "', '" + fields[1] + "', '" + fields[2] + "')"; // Execute the SQL statement to insert data into the SQL Server database using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand(insertSql, connection)) { int rowsAffected = command.ExecuteNonQuery(); } } } } Console.WriteLine("Data has been written to the SQL Server database."); Console.ReadLine(); } } }
In this example, the StreamReader
class is used to create a new instance of the reader to read data from the CSV file. The ReadLine
method of the StreamReader
object is used to read each line of data from the CSV file. The Split
method of the String
class is used to split each line of data into an array of fields. The SqlConnection
class is used to create a new instance of the connection to the SQL Server database. The Open
method of the SqlConnection
object is used to open the connection. The SqlCommand
class is used to create a new instance of the SQL command to insert data into the SQL Server database. The ExecuteNonQuery
method of the SqlCommand
object is used to execute the SQL statement and insert data into the SQL Server database.