我正在创建像包裹机一样的程序。我已连接到MySQL数据库。 正如你所看到的,我有字段“final int orderPassword”。我想通过我在本主题结尾处添加的方法自动生成它。“insert into”随机数到mysql db
public static void post() throws Exception{
final int parcelID = 2;
final int clientMPNumber = 777777777;
final int orderPassword = 1234;
try{
Connection con = getConnection();
PreparedStatement posted = con.prepareStatement("INSERT INTO Parcels.Orders (parcelID, clientMPNumber, orderPassword) VALUES ('"+parcelID+"', '"+clientMPNumber+"', '"+orderPassword+"')");
posted.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally{
System.out.println("Insert completed");
}
}
以下是我想要代替“final int orderPassword”的方法。
public static int generatePass(){
Random generator = new Random();
int orderPassword = generator.nextInt(9000)+1000;
return orderPassword;
}
我该怎么办?
如若'orderPassword'是唯一的? – Yahya
您还应该使用'PreparedStatement'的优点,并通过set-methods设置值。一个PreparedStatement不应该使用查询中的值创建 –