in table "skupina" we have values "pc1,pc2,pc3,...". But in this code I have result in mysql System.Collections.Generic.List
, but should be "pc1,pc2,pc3,....". Where is my mistake?
private void button1_Click(object sender, EventArgs e)
{
using (MySqlConnection cnn = new MySqlConnection("Server=10.7.18.35;Database=OitDB;Uid=martin;Pwd=;"))
{
MySqlDataAdapter da = new MySqlDataAdapter("SELECT namepc FROM skupina where nazovskup= 'mojask' ", cnn);
DataSet ds = new DataSet();
da.Fill(ds, "skupina");
List<string> skName = new List<string>();
foreach (DataRow row in ds.Tables["skupina"].Rows)
{
skName.Add(row["namepc"].ToString());
string constring = "Server=10.7.18.35;Database=OitDB;Uid=martin;Pwd=;";
var Query = "INSERT INTO OitDB.skup(uzivatel)VALUES('" + skName + "')";
MySqlConnection conDatabase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDatabase);
MySqlDataReader myReader;
try
{
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("Správa odoslaná!");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
You're implicitly calling ToString()
on a List<T>
. That doesn't do what you expect it to, because List<T>
doesn't override ToString()
. You can use
// Note: the ToArray() call is only required if you're targeting .NET 3.5, which
// is massively out of date, and really shouldn't be used IMO.
string.Join(", ", skName.ToArray())
to get a comma-separated result... but you really shouldn't do it where you're currently doing it. Instead, you should use parameterized SQL, e.g.
var query = "INSERT INTO OitDB.skup (uzivatel) VALUES (@name)";
...
cmdDatabase.Parameters.Add("@name", MySqlDbType.VarChar).Value
= string.Join(", ", skName.ToArray());
Always, always use parameterized SQL for values. You should only ever build SQL dynamically for non-value parts - and in that case you need to be really, really careful.
I would also suggest using using
directives for your command and data reader... and currently you've got two different connections open, which seems unnecessary...
See more on this question at Stackoverflow