userdetailsテーブルに別のテーブル(ログイン)からuserid(プライマリキーauto_increment)を取得する必要があります。それを実行しようとすると、私はこのエラー "不正な整数値を取得し続ける: 'LAST_INSERT_ID()'列 'userid'行1で"。windowsフォームを使用してC#で値をMysqlデータベースに追加する
私はLAST_INSERT_ID()を取り出し、query4の後に別のクエリを実行して値をユーザーIDに挿入しようとしましたが、新しい行を開く直前の行に挿入することができません。
これは実行しようとしているコードです。 '「」' "+" LAST_INSERT_ID() "+":
try
{
//This is my connection string i have assigned the database file address path
string MyConnection2 = "datasource=localhost;port=3310;database=e-votingsystem;username=root;password=Password12;";
//this is my insert query in which i am taking input from the user through windows forms
string Query2 = "INSERT INTO vote (username) VALUE ('" + usernameInputBox.Text + "');";
string Query3 = "INSERT INTO login (username,upassword) VALUE ('" + usernameInputBox.Text + "','" + passwordInputBox.Text + "');";
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUES ('" + nationalInsuranceInputBox.Text + "','"+"LAST_INSERT_ID()"+"','" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text+"');";
//This is MySqlConnection here i have created the object and pass my connection string.
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
//This is command class which will handle the query and connection object.
MySqlCommand MyCommand2 = new MySqlCommand(Query2, MyConn2);
MySqlCommand MyCommand3 = new MySqlCommand(Query3, MyConn2);
MySqlCommand MyCommand4 = new MySqlCommand(Query4, MyConn2);
MySqlDataReader MyReader2;
MySqlDataReader MyReader3;
MySqlDataReader MyReader4;
// opens new connection to database then executes command
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader(); // Here the query will be executed and data saved into the database.
while (MyReader2.Read())
{
}
MyConn2.Close();
// opens new connection to database then executes command
MyConn2.Open();
MyReader3 = MyCommand3.ExecuteReader();
while (MyReader3.Read())
{
}
MyConn2.Close();
//opens new connection to database the exexcutes command
MyConn2.Open();
MyReader4 = MyCommand4.ExecuteReader();
while (MyReader4.Read())
{
}
MyConn2.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
MessageBox.Show("Hello " + forename + surname, "read and accept the terms and conditions to continue");
//new termsAndConditionsPage().Show();
//Hide();
}
LAST_INSERT_IDは、同じ接続を使用して自動インクリメントフィールドに追加された最後のIDを返します。このコードから、同じ接続コンテキストを使用しているかどうかを理解することはできません。この前にコードを追加してください。 – Steve
1つの接続を使用してすべてのクエリを一緒に実行できますか? –
あなただけでなく、そうするべきです。 ExecuteReaderは、データの挿入に使用する正しい実行方法ではありません。それは動作しますが、そのロジックは、あなたが一部のデータがデータベースから戻ってきて、挿入がデータを返さないことを期待しています。 – Steve