Inserting values to mysql using c#

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi all,<br/>
In my application i want to insert multiple records at a time to mysql database. I am having a list of files in an array. I want to insert values of the files like id,name,path to mysql database. I tried the following, but it inserts only one file at a time.
How to insert multiple records with one query? <br/>
My code:<br/>
<div id="x_premain0" width="100%" style="display:block <img height="9" id="x_preimg0" src="http://www.codeproject.com/images/minus.gif" width="9" style=" <span id="x_precollapse0" style="margin-bottom:0pt Collapse<span> |
http://www.codeproject.com/Questions/333647/Inserting-values-to-mysql-using-csharp# Copy Code
<pre id="x_pre0" style=" MySqlConnection conn = <span class="x_code-keyword new MySql.Data.MySqlClient.MySqlConnection();
MySqlCommand cmd = <span class="x_code-keyword new MySql.Data.MySqlClient.MySqlCommand();

string SQL;

conn.ConnectionString = <span class="x_code-string "<span class="x_code-string server=localhost; userid=root;password=;database=test;";
conn.Open();



<span class="x_code-keyword try
{
string[] files = Directory.GetFiles(<span class="x_code-string @"<span class="x_code-string E:voices", <span class="x_code-string "<span class="x_code-string *.wav");
foreach (string file <span class="x_code-keyword in files)
{


string filename = Path.GetFileName(file);
string directory = Path.GetFullPath(file);
cmd.Parameters.AddWithValue(<span class="x_code-string "<span class="x_code-string @dwnfile_name", filename);
cmd.Parameters.AddWithValue(<span class="x_code-string "<span class="x_code-string @dwnfile_path", directory);

SQL = <span class="x_code-string "<span class="x_code-string insert into sdwn_files(dwnfile_id,dwnfile_name,dwnfile_path) values(NULL, @dwnfile_name, @dwnfile_path)";
cmd.Connection = conn;
cmd.CommandText = SQL;
cmd.ExecuteNonQuery();


MessageBox.Show(<span class="x_code-string "<span class="x_code-string Files Inserted into database successfully!",
<span class="x_code-string "<span class="x_code-string Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);




}

conn.Close();
}
<span class="x_code-keyword catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(<span class="x_code-string "<span class="x_code-string Error " + ex.Number + <span class="x_code-string "<span class="x_code-string has occurred: " + ex.Message,
<span class="x_code-string "<span class="x_code-string Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}



}
[/code]
Thanks in advance<hr class="sig psgviscom

View the full article
 
Back
Top