在Mysql中获取表的外键字段中的空值

时间:2014-02-04 05:31:44

标签: java mysql

I have 2 tables in my application:
1.newuser
2.introducer_table

Newuser1 table contains *sid**(primary key,auto-generated field)****,  fathername,gender,datebirth,occupation,addharnumber as columns

1.我正在使用java预编译语句将值插入到newuser表中:

PreparedStatement pst =  con.prepareStatement("insert into newuser1 (name,fathername,gender,datebirth,occupation,aadharNumber) values(?,?,?,?,?,?)");

          //pst.setString(1,NULL);
          pst.setString(1,”xyz”);
          pst.setString(2,"ram");
          pst.setString(3,"male");
          pst.setString(4,"oct25");
          pst.setString(5,"emps");
          pst.setString(6,"4564");
data is inserted successfully,but I want the sid value of newuser1 in my  introducer_table so I write the query like this in prepared statement to select the last   insert  id.

My introducer_table contains the columns: 

**sid(foreign key),name,accountno,sign**
PreparedStatement pst =  con.prepareStatement("insert into    introducer_table(sid,name,accountno,sign) values((SELECT LAST_INSERT_ID() from   dual),?,?,?)");

              //nomine details into data base
              //pst.setString(1,NULL);
              pst.setString(1,"ram");
              pst.setString(2,"8945");
              pst.setString(3,"ssss");

 When I execute this,Im getting ‘0’ value in the sid column of introducer_table.I make   sid column as not null while creating intoducer_table,even im getting the ‘zero’ value like this:

Introducer_table:

**Sid**   name   accountno     sign
**0**     ram      8945        ssss

请帮助我这么多天我被这个问题困扰了。

1 个答案:

答案 0 :(得分:0)

而不是按照自己的方式考虑使用

con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);

然后插入

pst.executeUpdate();
ResultSet rs = prest.getGeneratedKeys();

int last_inserted_id = -1;
if(rs.next())
{
  last_inserted_id = rs.getInt(1);
}