I have created a string array by parsing a long CSV string (read from a .csv file) into its elements (i.e. the bits that are actually seperated by commas). I now wish to add those elements to an SQL Server 2005 database table that I have already created for that purpose.
Can someone please point me at a simple example of how to loop thru the array and add the elements to the appropriate fields of a database.
I am using Visual Studio 2008, C#.NET.
Thanks.
Loading

CrishRank #1,487 · 1.1K reputationPosted May 12, 2010, 10:01 PM EDT
Get data from CSV file use below code.
StreamReader sr = new StreamReader("file.csv");
string inputLine = "";
String[] values = null;
while ((inputLine = input.ReadLine()) != null)
{
values = inputLine.Split(";");
}
input.Close();
Steve Geard4 reputationPosted May 13, 2010, 3:17 PM EDT
Where I need the help is looping thru the string array and adding each element to a row in a previously created SQL Server database.
Matej Skerjanc3 reputationPosted Jun 8, 2010, 5:03 AM EDT
foreach(string x in stringarray[])
{
then you can create data row and fill x into it, and add row to datatable...
really depending on your database organisation
}
ahsan ashfaq14 reputationPosted Jul 13, 2010, 9:52 PM EDT
-------------------------------
string query
query="insert into table values('"
foreach(string x in stringarray[])
{
query=query+x+"',"
}
query=left(query,(query.length-2)) //Removing last extra comma, please check the indexes
query=query+")"
//here you have your query to run
Sam HobbsRank #107 · 20.5K reputationPosted Jul 14, 2010, 9:35 PM EDT
The main portion that connects to the database and creates the insert command is:
SqlCeConnection Connection = new SqlCeConnection(ConnectionString); try { Connection.Open(); } catch (Exception ex) { Console.WriteLine("Open error: {0}", ex.ToString()); return; } const String CommandText = "Insert Into People (First, Last) Values (@First, @Last)"; SqlCeCommand InsertCommand = new SqlCeCommand(CommandText, Connection); SqlCeParameter p = null; p = InsertCommand.Parameters.Add("@First", SqlDbType.NVarChar, 50, "First"); p.SourceVersion = DataRowVersion.Original; p = InsertCommand.Parameters.Add("@Last", SqlDbType.NVarChar, 50, "Last"); p.SourceVersion = DataRowVersion.Original; InsertPerson(InsertCommand, "John", "Smith"); InsertPerson(InsertCommand, "Bill", "Johnson"); InsertPerson(InsertCommand, "Brooke", "Dudley"); Connection.Close();And then my InsertPerson function is:
static void InsertPerson(SqlCeCommand InsertCommand, String First, String Last) { InsertCommand.Parameters["First"].Value = First; InsertCommand.Parameters["Last"].Value = Last; try { InsertCommand.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine("Insertion error: {0}", ex.ToString()); } }