如何解决在SQL Developer中使用JDBC将一个表主键插入另一个表主键
我有2个表,我想将一个表主键插入另一个引用第一个表的主键。 表1具有EMP_ID(主键),EMP_CODE 表2具有EMP_ID(外键引用表1),EMP_DET,EMP_SAL
请参阅下面的错误代码
import java.sql.*;
import javax.swing.JOptionPane;
public class merge {
public static void main(String[] args ) {
String url = "jdbc:oracle:thin:@localhost:1521:d12fr13";
String user = "username";
String pass = "username";
Connection con =null;
int EMP_ID =0;
PreparedStatement ps = null;
String inserttable1 = "INSERT INTO TABLE1 (EMP_CODE) VALUES (?)";
String inserttable2 ="INSERT INTO TABLE2 (EMP_ID,EMP_DET,EMP_SAL) VALUES (?,?,?)";
ResultSet generatedKeys = null;
try (Connection myConn = DriverManager.getConnection(url,user,pass);)//Connection
{
myConn.setAutoCommit(false);//Turn off auto commit
try (PreparedStatement myPs = myConn.prepareStatement(inserttable1,Statement.RETURN_GENERATED_KEYS))//Prepared Statement
{
myPs.setInt(1,100);
myPs.executeUpdate();
myConn.commit();
generatedKeys = myPs.getGeneratedKeys();
if (generatedKeys.next())//Return ID
{
EMP_ID= generatedKeys.getInt(1);
}
else
{
throw new SQLException("No generated EMP_ID returned");
}
}//end of try
finally
{
if (generatedKeys != null) generatedKeys.close();
}//end of finally
try (PreparedStatement myPs = myConn.prepareStatement(inserttable2))//Prepared Statement
{
myPs.setInt(1,EMP_ID);
myPs.setInt(2,101);
myPs.setInt(3,102);
myPs.executeUpdate();
myConn.commit();
JOptionPane.showMessageDialog(null,"Insert Successful");
}//end of try
}
}
错误: 线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:0 在oracle.jdbc.driver.JavaToJavaConverter.main(JavaToJavaConverter.java:2552)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。