如何在javajframe表中插入递增的主键和外键?

7d7tgy0s  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(265)

我是java新手,正在尝试将数据插入netbeans jframe上的三个表中。我已经在mysql上创建了数据
第一个表包含主键

create table TraineeDetals(
TraineeID smallint unsigned not null auto_increment primary key,
FirstName varchar(100) not null,
MiddleName varchar(100) not null,
LastName varchar(100) not null
)

另一个表有外键

create table CollegeDetails(
collegeName varchar(100) not null,
Specialization varchar(100) not null,
TraineeID smallint unsigned not null,
constraint 'fk_Trainee'
foreign key (TraineeID) references TraineeDetails (TraineeID)
on delete cascade
on update restrict
)

现在我想使用jframe插入数据,所以在java代码中我做到了这一点

String url="jdbc:mysql://localhost/mysql";
   String user="root";
   String pass="root";

   private void 
   SaveButtonActionPerformed(java.awt.event.ActionEvent evt) {  

   try{

        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection(url, user, 
        pass);
        String sql="Insert into TraineeDetails 
        (FirstName,MiddleName,LastName)values(?,?,?)";
        PreparedStatement pst =con.prepareStatement(sql);

        pst.setString(1, firstNameTextFiled.getText());
        pst.setString(2, MiddleNameTextField.getText());
        pst.setString(3, LastNameTextField.getText());

        String sql2 = "Insert into CollegeDetails (CollegeName, 
        Specialization,TraineeID)values(?,?,?)";
        PreparedStatement pst2 =con.prepareStatement(sql2);

        pst2.setString(1, CollegeNameTextField.getText());
        pst2.setString(2, SpecializationTextField.getText());
        pst.setString(3, TraineeIDTextField.getText());

        pst.executeUpdate();
        pst2.executeUpdate();

        JOptionPane.showInputDialog(this,"Insert 
        Successfully");

        clearText();

    }
    catch(Exception e)
    {
        JOptionPane.showInputDialog(this,e.getMessage());
    }
    }

此代码仅显示表TraineDetails的数据
所有数据都必须从这里添加,id必须是自动递增的。

之后,管理员可以显示他在这里添加的数据。jframe只显示TraineDetails表的数据如何修复它

请问,我要做什么插入自动递增主键和外键,并显示数据一起添加后?我的java代码呢,有什么遗漏吗?

lvmkulzt

lvmkulzt1#

你可以看这个视频,以便更好地了解如何做到这一点https://www.youtube.com/watch?v=nc6by2ojr7s
你可以这样做。。。
首先让类名为sql.java并将其导入到您的项目类库中
把这段代码写进去

import java.sql.PreparedStatment;

public class sql {
public void id_incrementtable() {

int id = 1 ;
PreparedStatment ps = null;
ResultSet rs = null ; 
Conectar db = new Conectar() ;
try {
ps = db.getConnection().prepareStatement("select max(id) from your 
tablename");
rs = ps.executeQuery();
while(rs.next()) (
id = rs.getint(1) + 1 ; 
)
}catch(Exception ex);

System.out.printin("error"+ex.getMessage());

}
finally ( 
try (
ps.close();
rs.close();
db.desconectar() ;
) catch(Exception ex) ( 

)

}

//通过运行上面的命令,每次在表中保存记录时,您都会注意到它在表名中添加了auto serial
//保存数据按钮代码时,首先定义sql s=newsql(),以便从添加到项目类引用中的//类中读取
sql s=新sql();int id=s.id_incrementable();
//你把剩下的代码放在这里。。。我想你明白了

相关问题