简体   繁体   中英

How to write query in java to insert data with foreign keys using MySql

Table 1 :questions(qid,category,question);  PRIMARY KEY:qid,category  
Table 2 :choices(ch_id,qid1,category1,choice);  PRIMARY KEY: ch_id  

Here qid, ch_id use AUTO_INCREAMENT.

Sql Query:

mysql>INSERT INTO choices(qid1,category1,choie)  
->SELECT qid,category,'Some Choice'  
->FROM questions 
WHERE qid1=qid AND category1=category;  

With this scenario how would I write this code for java with the same query.

First, you need an instance of java.sql.Connection. Depending from the context, there are various ways to obtain one, but if you are using some kind of Java EE container, like Tomcat, for example, you will want to use a javax.sql.DataSource (another way, without a Java EE server, would be using a java.sql.DriverManager, but it's less efficient). There also various ways to get a DataSource, but the most common looks like this:

String jndiName = "java:comp/env/jdbc/myDB";
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup(jndiName);

This will use the database connection you have set up in your Tomcat configuration.

After that, you need a Connection:

Connection con = ds.getConnection();

And then a java.sql.Statement, the class used to execute a SQL statement:

Statement stmt = con.createStatement();

Now, you can execute your SQL code:

stmt.execute("INSERT INTO choices(qid1,category1,choie) SELECT qid,category,'Some Choice' FROM questions WHERE qid1=qid AND category1=category;");

Are we done? No, we aren't. We need to manage our transactions, by adding some specific code and Exception handling, and we need to release the various database resources we are using in order to be able to reuse them later. We do that in the finally block so we are sure it get executed. At the end, the whole thing looks like this (untested code!):

try {
    String jndiName = "java:comp/env/jdbc/myDB";
    Context ctx = new InitialContext();
    DataSource ds = (DataSource)ctx.lookup(jndiName);
    Connection con = ds.getConnection();
    con.setAutoCommit(false); // Transaction are managed manually
    Statement stmt = con.createStatement();
    stmt.execute("INSERT INTO choices(qid1,category1,choie) SELECT qid,category,'Some Choice' FROM questions WHERE qid1=qid AND category1=category;");
    con.commit(); // Transaction OK
} catch (SQLException sqle) {
    con.rollback(); // Transaction not OK
} finally {  //Resource management
    if (stmt!=null) {
        stmt.close();
    }
    if (con != null) {
        con.close();
    }
}

You should take a look in the Javadoc. A good starting point:

http://docs.oracle.com/javase/6/docs/api/javax/sql/DataSource.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM