我試圖從文本框插入到表中的值,並從另一個表中檢索一個外鍵ID並插入它也。從文本框和從另一個表的外鍵插入值到表#C#
所以我有一個包含用戶ID一個用戶表,我想這個插入的營養日記,其中包括所有來自文本框的數據(即體重,身高,日期等)
我通過檢索成員Id使用會話來跟蹤用戶名(lblRegistered) 這裏是我的代碼:
SqlConnection con = new SqlConnection("path for my connection");
con.Open();
SqlCommand cmd = new SqlCommand("select COUNT(*)FROM Members where Username='" + lblRegistered.Text + "'", con);
con.Close();
con.Open();
cmd.CommandText = "INSERT INTO Nutrition(Weight, Height, Bmi, Date, WaterIntake, CalorieIntake, MemberId) values ('" + txtWeight.Text + "','" + txtHeight.Text + "','" + txtBmi.Text + "','" + txtDate.Text + "','" + txtWater.Text + "','" + txtCalorie.Text + "', Select Users.UserId From Users where (Users.Username= '" + lblRegistered.Text + "'))";
cmd.ExecuteNonQuery();
cmd.Clone();
con.Close();
Response.Redirect("Success.aspx");
的誤差接近選擇用戶的一部分。
任何幫助將不勝感激!
您在count和 –
@ Selman22之間缺少一個空格這仍然是有效的SQL。我相信問題來自於嘗試在一個命令中執行「INSERT」和「SELECT」。你應該首先執行'SELECT',將它存儲在一個變量中,並將它傳遞給'INSERT'。 – TTeeple
謝謝你們。我對此很陌生,所以我不確定我會怎麼做。那會包括使用執行標量嗎? 以下內容: SqlCommand cmd2 = new SqlCommand(「select MemberId FROM Members where Username ='」+ lblRegistered.Text +「'」,con); int UserId; UserId = Convert.ToInt32(cmd2.ExecuteScalar()); 然後在值中有'UserId'? – user3249809