2016-12-13 9 views
1

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(); 
} 
+0

LAST_INSERT_IDは、同じ接続を使用して自動インクリメントフィールドに追加された最後のIDを返します。このコードから、同じ接続コンテキストを使用しているかどうかを理解することはできません。この前にコードを追加してください。 – Steve

+0

1つの接続を使用してすべてのクエリを一緒に実行できますか? –

+0

あなただけでなく、そうするべきです。 ExecuteReaderは、データの挿入に使用する正しい実行方法ではありません。それは動作しますが、そのロジックは、あなたが一部のデータがデータベースから戻ってきて、挿入がデータを返さないことを期待しています。 – Steve

答えて

0

、あなたは、単一引用符の間LAST_INSERT_IDを持っており、これは、実行する文の文字列リテラルではない、それを変換します。ただし、引用符を削除しても、ログインテーブルのAUTOINCREMENT番号とは異なる接続を使用してLAST_INSERT_IDを取得できるかどうかはわかりません。いずれにせよ、あなたは異なるアプローチを使用する必要がありますと、最初のものとして、あなたはできるだけ早く、文字列の連結及び利用パラメータを削除する必要があります(理由:Sql Injectionまたは姓=オニール)

string Query2 = "INSERT INTO vote (username) VALUE (@uname)"; 
string Query3 = @"INSERT INTO login (username,upassword) VALUE (@uname, @upass); 
        SELECT LAST_INSERT_ID();"; 
string Query4 = @"INSERT INTO userdetails 
        (nationalinsurance,userid,forename,middlename, 
        surname,housenumber,street,towncity,postcode,suffix) 
        VALUES (@insurance, @userid, @forename, @middlename, 
        @surname, @housenum, @street, @town, @postcode, @suffix)"; 

オープン一つだけの接続と3つのコマンドをすべて使用ステートメントの間に作成する

using(MySqlConnection con = new MySqlConnection(.....constring here....)) 
using(MySqlCommand cmd2 = new MySqlCommand(Query2, con)) 
using(MySqlCommand cmd3 = new MySqlCommand(Query3, con)) 
using(MySqlCommand cmd4 = new MySqlCommand(Query4, con))  
{ 
     con.Open(); 

     // Add the parameter to the first command 
     cmd2.Parameters.Add("@uname", MySqlDbType.VarChar).Value = usernameInputBox.Text; 
     // run the first command 
     cmd2.ExecuteNonQuery(); 

     // Add parameters to the second command 
     cmd3.Parameters.Add("@uname", MySqlDbType.VarChar).Value = usernameInputBox.Text; 
     cmd3.Parameters.Add("@upass", MySqlDbType.VarChar).Value = passwordInputBox.Text; 

    // Run the second command, but this one 
    // contains two statement, the first inserts, the 
    // second returns the LAST_INSERT_ID on that table, we need to 
    // catch that single return 
    int userID = (int)cmd3.ExecuteScalar(); 

    // Run the third command 
    // but first prepare the parameters 
    cmd4.Parameters.Add("@insurance", MySqlDbType.VarChar).Value = nationalInsuranceInputBox.Text; 
    cmd4.Parameters.Add("@userid", MySqlDbType.Int32).Value = userID; 
    .... and so on for all other parameters 
    .... using the appropriate MySqlDbType for the column type 
    cmd4.ExecuteNonQuery(); 
} 
+0

ありがとうございました。 –

0

あなたの現在のクエリがエラー

string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUE ('" + nationalInsuranceInputBox.Text + "','"+"LAST_INSERT_ID()"+"','" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text + "');SELECT LAST_INSERT_ID();" 

を持っているあなたが持っているあなたのテキストのクエリ文字列に添付クエリ

+0

テーブルのuserdetailsのuseridフィールドにLAST_INSERT_IDを挿入する際に「修正」が役立つ理由を説明できますか? – Steve

0

を試してみてください、 '' "LAST_INSERT_ID()"の前後にある "、"は、LAST_INSERT_ID()を間違って単一引用符で囲んでいることに注意してください。

は、次のクエリをお試しください:としては、他の回答で説明

string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUE ('" + nationalInsuranceInputBox.Text + "',"+"LAST_INSERT_ID()"+",'" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text + "');"; 
+0

完全なクエリ文字列には、隣接する用語の前後にシングルトンの引用符があります。ですから、私が正しく与えた文字列は、 'previousterm'、LAST_INSERT_ID()、 'nextterm' ...という結果になりました。あなたはカンマが必要だと思います。そして、はい、彼はSQLインジェクションから身を守るべきです。 – Brian

+0

Misread、口実。 – RandomStranger

関連する問題