I been trying different things to get my code to work.
I'm pretty new with both c# and with DB. But the thing is i am trying to fix a db for a Music event where i add in band names and there members.
I have 2 tables. One with Band and one with Band Members. I am using MySQLCommand in visual studio C#
My button code for the insertion of code to a MySQL Class
private void bt_LäggTill_Band_Medlem_Click(object sender, EventArgs e)
{
MySql mySQL = new MySql();
MySqlConnection myConn = mySQL.GetServer();
// string insert = @"Insert Into BandMedlemar(BNamn , MedlemsNamn)Values ('" + cb_Band_Medlemar.Text.ToString() + "',(Select BNamn from Band Where BNamn = '" + cb_Band_Namn.Text.ToString() + "'))";
// string insert = "Insert Into BandMedlemar(MedlemsNamn , BNamn) Select val.MedlemsNamn , f.BNamn from (Values ('" + cb_Band_Medlemar.Text.ToString() + "','" + cb_Band_Namn.Text.ToString() + "')) val(MedlemsNamn,BNamn) Left Join Band f Useing (BNamn)";
string insert =
"Insert Into BandMedlemar(MedlemsNamn , BNamn) " +
"Select '" + cb_Band_Medlemar.Text.ToString() + "' , BNamn " +
"From Band Where BNamn='" + cb_Band_Namn.Text.ToString() + "'";
int count = 1;
string para = cb_Band_Medlemar.Text.ToString().Replace(" ", "");
string para2 =cb_Band_Medlemar.Text.ToString();
mySQL.Insert(myConn, insert, count, para, para2);
Update();
}
I tried a couple things i let them be there.
and then there is my SQL code that takes the data end sends in to the database
public void Insert(MySqlConnection myConn , string text , int count , string para , string para2)
{
try
{
myConn.Open();
MySqlCommand cmd = new MySqlCommand(text, myConn);
//cmd.Connection = myConn;
//cmd.CommandText = text;
cmd.Prepare();
string[] splited = para.Split('@');
string[] splited2 = para2.Split('@');
int number = 0;
while (count != 0)
{
cmd.Parameters.AddWithValue("@" + splited[number], splited2[number]);
count--;
number++;
}
cmd.ExecuteNonQuery();
myConn.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
myConn.Close();
}
}
the code works with normal insert with multiple parameters as well.
for more info i post my Create table for the band members
CREATE TABLE BandMedlemar
( BNamn varchar(20) NOT NULL default '',MedlemsNamn varchar(30) NOT NULL,
Info varchar(50) default NULL, PRIMARY KEY (BNamn),
CONSTRAINT BandMedlemar_ibfk_1 FOREIGN KEY (BNamn) REFERENCES Band (BNamn)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
As Primary key foreign key relationship is there, please help me how i could be able to add more then one member of a band
Please give me the proper solution as i am not getting it.