![](/img/trans.png)
[英]how to insert incremented primary key and foreign key in java jframe tables?
[英]How to add to INSERT INTO PRIMARY KEY AND FOREIGN KEY
所以我有兩個表:locations 和雇員我希望locations_id
在employees.locations_id
是相同的,我試圖在一個語句中全部做到這一點,錯誤是這樣你的SQL 語法有錯誤; 檢查與您的 MySQL 服務器版本相對應的手冊,了解在第 1 行的 'INSERT INTO 員工(employees_id,locations_id)VALUES('e1598','')' 附近使用的正確語法
String sql = " INSERT INTO locations( locations_id , username, password, id, type_of_id, first_name, last_name, phone, email, date_of_birth, address, sex ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"
**Error here --->** + "INSERT INTO employees(employees_id,locations_id) VALUES (?,SELECT locations_id FROM locations INNER JOIN employees ON locations.locations_id =employees.locations_id)";
try {
MicroModelGUI micro = new MicroModelGUI();
PreparedStatement consulta = micro.connection.prepareStatement(sql);
consulta.setString(1, tflid.getText());
consulta.setString(2, tfuser.getText());
consulta.setString(3, tfpass.getText());
consulta.setString(4, tfid.getText());
consulta.setString(5, tftoid.getText());
consulta.setString(6, tffirst.getText());
consulta.setString(7,tflast.getText());
consulta.setString(8,tfphone.getText());
consulta.setString(9,tfemail.getText());
consulta.setString(10,tffdn.getText());
consulta.setString(11,tfaddress.getText());
consulta.setString(12,tfsex.getText());
consulta.setString(13,tfeid.getText());
int resultado = consulta.executeUpdate();
您應該使用INSERT INTO ... SELECT
在此處INSERT INTO ... SELECT
:
INSERT INTO employees (employees_id, locations_id)
SELECT ?, l.locations_id
FROM locations l
INNER JOIN employees e ON l.locations_id = e.locations_id;
到?
占位符,您將從 Java 代碼中綁定一個值。 請注意,雖然您的 SQL 版本可能支持將標量子查詢放入VALUES
子句中,但您的確切版本很可能會導致錯誤,因為它會返回多行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.