我是一个非常新的自学生,我试图在不同的表中插入数据,但使用相同的ID,并为选项卡3设置默认日期,如2000/01/01: 我的表就像:
TAB1 ID1 varchardate1
TAB2 ID ID1 varchardate2
TAB3 ID ID1 日期时间
我正在使用该代码在tab1中插入数据:
String sub1 = "Insert Into tab1 (`varchardate1`) values "
+ "(" + jTextField1.getText() + "')";
System.out.println(sub1);
现在我可以做同样的事情,但我想保存那个Id1并将其用于其他2个表格,而对于tab3我想设置默认日期时间2000/01/01。
感谢您的帮助。
答案 0 :(得分:1)
据我所知: 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();
}
}
persistance framework
JPA
或Hibernate的{{1}}的最佳做法
醇>