I have an issue on how to insert a value from another table into a new one. I have the following code:
Scanner scanner1 = new Scanner(System.in);
java.sql.Statement st = conn.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM flight");
int f_id = scanner.nextInt();
int air_id = scanner.nextInt();
while (res.next()) {
if (Integer.parseInt(res.getString("air_id")) == air_id && Integer.parseInt(res.getString("f_id")) == f_id) {
if (Integer.parseInt(res.getString("f_status_f_id_s")) > 0) {
System.out.println("You can reserve");
stmt=(Statement) conn.createStatement();
stmt.execute("SET FOREIGN_KEY_CHECKS=0");
String query1= "INSERT INTO reservations" +" VALUES(1,6/6/2020,)"+air_id+"(..,..,;
stmt.executeUpdate(query1);
To be more specific on the line String query1= "INSERT INTO reservations" +" VALUES(1,6/6/2020,)"+air_id+"(..,..,; I want the air_id to be the value I scanned before such as f_id. Is this the right syntax way to do it?
You can insert the variable in your query by using the following code:
String query1= "INSERT INTO reservations" +" VALUES(1,6/6/2020,)"+air_id=@air_id+"(..,..,;
Thank you, I hope it helps you
Use Prepared Statements to that .i.e:
PreparedStatement stmt= con.prepareStatement();
stmt.execute("SET FOREIGN_KEY_CHECKS=0");
//put ?(no of values you need to insert)
String query1= "INSERT INTO reservations values(?,?,?)";
stmt.setInt(1,1);//1 specifies the first parameter in the query
stmt.setString(2,"6/6/2020");
stmt.setInt(3,air_id);//pass your variable
stmt.executeUpdate(query1);