1

Good day!

I have a code here that inserts, but never updates. There error I get is Parameter '@id_number' must be defined.

My code:

string query = "INSERT INTO pupil (`fname`, `lname`, `mi`) VALUES (@fn, @ln, @mi)";
MySqlCommand com = new MySqlCommand(query, connection);

com.Parameters.AddWithValue("@fn", txtAddFName.Text);
com.Parameters.AddWithValue("@ln", txtAddLName.Text);
com.Parameters.AddWithValue("@mi", txtAddMI.Text);
com.ExecuteNonQuery();

//create ID number
long lastID = com.LastInsertedId;
int length = 4;
string currentYear = DateTime.Now.Year.ToString("yy");
string result = lastID.ToString().PadLeft(length, '0');
string id_number = currentYear + "-" + result ;
string updateIDNumber = "UPDATE pupil SET id_number=@id_number WHERE pupil_id=@pupil_id";
MySqlCommand IDcom = new MySqlCommand(updateIDNumber, connection);

com.Parameters.AddWithValue("@id_number", id_number);
com.Parameters.AddWithValue("@pupil_id", lastID);
IDcom.ExecuteNonQuery();

The Insert code works, but the Update isn't. What I wanted to do is to get the last inserted ID and update it's field id_number with the last 2 digits of the current year + the last inserted ID with 4 leading 0's. For example if the last Inserted ID is 1, the value of lastID variable will be 16-0001.

The schema by the way is this:

pupil_id INT(11) AUTO_INCREMENT
fname VARCHAR(50)
lname VARCHAR(50)
mi VARCHAR(50)
id_number VARCHAR(255)

Any help would be much appreciated.

2 Answers 2

2

You are using the wrong command instance:

com.Parameters.AddWithValue("@id_number", id_number);
com.Parameters.AddWithValue("@pupil_id", lastID);

Instead of com just use IDcom

IDcom.Parameters.AddWithValue("@id_number", id_number);
IDcom.Parameters.AddWithValue("@pupil_id", lastID);
Sign up to request clarification or add additional context in comments.

3 Comments

@cableload It's okay, still give you an up :)
By the way guys, it works but I got yy-0001 instead or 16-0001
Use DateTime.Now.ToString("yy")without Yearproperty. Consider to accept as an answer if it works.
1

You declared a second MySqlCommand IDcom and so you should add parameters for that.You were adding params to the older command object.

IDcom.Parameters.AddWithValue("@id_number", id_number);
IDcom.Parameters.AddWithValue("@pupil_id", lastID);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.