Answer the question
In order to leave comments, you need to log in
How to put value from one related MySql table to another when working in Visual Studio in C#?
Good afternoon everyone! C ran into a problem while creating a knowledge testing program.
I have 3 tables created in phpMyAdmin: questions, subjects, answers.
The subjects table contains the following fields: ID, subject_name, subject_title,
The answers table contains the following fields: ID, answer_1, answer_2, answer_3, answer_4, true_answer
The questions table contains the following fields: ID, question_text, ID_answer, ID_subject
The ID_answer, ID_subject fields of the questions table are associated with The IDs of the other two tables.
When entering information in the application, the following error pops up "Field 'ID_answer' doesn't have a default value"
Form in the screenshot.
private void btn_added_Click(object sender, EventArgs e)
{
string sql = "INSERT INTO vedar_bd.answers(answer_1, answer_2, answer_3, answer_4, true_answer) VALUES (@a1, @a2, @a3, @a4, @ta)";
string sql2 = "INSERT INTO vedar_bd.subjects(subject_name, subject_title) VALUES(@sn, @st)";
string sql3 = "INSERT INTO vedar_bd.questions(question_text) VALUES (@qt)";
string connStr = @"server=localhost; port=3306; username=root; password= root; database=vedar_bd;";
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
MySqlCommand command = new MySqlCommand(sql, conn);
command.Parameters.Add("@a1", MySqlDbType.VarChar, 250);
command.Parameters.Add("@a2", MySqlDbType.VarChar, 250);
command.Parameters.Add("@a3", MySqlDbType.VarChar, 250);
command.Parameters.Add("@a4", MySqlDbType.VarChar, 250);
command.Parameters.Add("@ta", MySqlDbType.VarChar, 250);
command.Parameters["@a1"].Value = txt_answer_1.Text;
command.Parameters["@a2"].Value = txt_answer_2.Text;
command.Parameters["@a3"].Value = txt_answer_3.Text;
command.Parameters["@a4"].Value = txt_answer_4.Text;
command.Parameters["@ta"].Value = txt_answer_true.Text;
command.ExecuteNonQuery();
MySqlCommand command2 = new MySqlCommand(sql2, conn);
command2.Parameters.Add("@sn", MySqlDbType.VarChar, 250);
command2.Parameters.Add("@st", MySqlDbType.VarChar, 250);
command2.Parameters["@sn"].Value = txt_subject.Text;
command2.Parameters["@st"].Value = txt_title.Text;
command2.ExecuteNonQuery();
MySqlCommand command3 = new MySqlCommand(sql3, conn);
command3.Parameters.Add("@qt", MySqlDbType.VarChar, 250);
command3.Parameters["@qt"].Value = rtxt_question.Text;
command3.ExecuteNonQuery();
conn.Close();
}
Answer the question
In order to leave comments, you need to log in
Everything turned out to be very simple. In the first two requests I added SELECT last_insert_id()
, and the result was placed in int i = Convert.ToInt32(command.ExecuteScalar());
Further, I think that everything is clear.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question