0

im a pretty new self student and i am trying to insert Data in different tables but using same ID like that and for the tab 3 set a default Date like 2000/01/01: My tables are like:

tab1 Id1 varchardate1

tab2 ID Id1 varchardate2

tab3 ID Id1 datetime

Im using that code to insert Data in the tab1:

String sub1 = "Insert Into tab1 (`varchardate1`) values "
                    + "(" + jTextField1.getText() + "')";
            System.out.println(sub1);

Now i can do the same but i want to save that Id1 and use it for the other 2 tables and for tab3 i want to set that default datetime 2000/01/01.

Thanks for the help in advance.

user2853957
  • 73
  • 1
  • 1
  • 7
  • My bad. I posted a PHP solution for a Java question. You might wanna look here http://stackoverflow.com/questions/1915166/how-to-get-the-insert-id-in-jdbc – Dipen Shah Jul 09 '15 at 14:51

1 Answers1

1

From what I understood: import java.sql.*;

  static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
  static final String DB_URL = "jdbc:mysql://localhost/EMP";
  String txtfld =  jtextField.getText();

try{
      // register the JDBC driver
     Class.forname("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
    String query = "INSERT INTO tab1(varchardate1) VALUES(?)";    
    PreparedStatement stmt = conn.preparedStatement(query);
    // set prepared statements in the order you have the columns
    stmt.setString(1,txtfld);
    stmt.executeUpdate();

   String query2 = "SELECT id FROM tab1 WHERE varchardate1 = ?";
   PreparedStatement stmt2 = conn.preparedStatement(query2);
   stmt.setString(1, txtfld );
   ResultSet result = stmt.executeQuery(query2);

   int  tab1Id = result.getInt('id');

   //at this point just insert the next
   // to values with the `id` extracted from first insertion

} catch (SQLException e) {

        System.out.println(e.getMessage());

    } finally {

        if (preparedStatement != null) {
            preparedStatement.close();
        }

        if (dbConnection != null) {
            dbConnection.close();
        }

    }
  1. use Prepared Statements for security purposes when inserting data into a database
  2. Best practice to learn a persistance framework like Hibernate or EJB which uses JPA
Esteban Rincon
  • 2,040
  • 3
  • 27
  • 44