[英]How to insert auto increment values to mysql from java
try
{
String ptype = null;
if(b1.isSelected())
{
ptype="cash";
}
else if(b2.isSelected())
{
ptype="cred";
}
String rID=ridt.getText();
String cID=cidt.getText();
double Rcharge=Double.parseDouble(rct.getText());
double Mcharge=Double.parseDouble(mct.getText());
double total=Double.parseDouble(tott.getText());
double sum=Double.parseDouble(casht.getText());
double change=Double.parseDouble(balt.getText());
String sql0 ="INSERT INTO transactions(transaction_id,reservation_id,cus_id,room_charges,meal_charges,total_amount,cash,change,payment_type,emp_id)values('"+?+"','"+rID+"','"+cID+"','"+Rcharge+"','"+Mcharge+"','"+total+"','"+sum+"','"+change+"','"+ ptype+"','e010')";
pst=conn.prepareStatement(sql0);
pst.execute();
}
catch(NumberFormatException | SQLException e)
{
System.out.println(e);
}
在上面的sql語句中transaction_id是一個自動遞增字段。 如何將該值插入表格? 如果我在代碼中保留了該值,是否會將其添加到數據庫的表中?
auto increment
意味着當records
插入到表中時該field
自動遞增。 如果要自定義輸入id
到字段transaction_id
,請將其字段類型更改為int
, tinyint
或其他類型,具體取決於傳遞值的類型。
如果該字段映射為auto_increment,則不應在查詢中傳遞該字段,而應在數據庫級別進行。
另外,如果您正在使用prepareStatment ,請正確使用它。
在prepareStatement中,如果要使用create語句執行此操作,請不要在查詢中直接傳遞動態值。
在安全性方面,PreparedStatments更好,請檢查此以供參考Statement和PreparedStatement之間的區別
請檢查修改后的代碼,我刪除了自動生成的字段,並進行了查詢,因為它應該用於prepareSatements
String rID=ridt.getText();
String cID=cidt.getText();
double Rcharge=Double.parseDouble(rct.getText());
double Mcharge=Double.parseDouble(mct.getText());
double total=Double.parseDouble(tott.getText());
double sum=Double.parseDouble(casht.getText());
double change=Double.parseDouble(balt.getText());
String sql0 ="INSERT INTO transactions(reservation_id,cus_id,room_charges,meal_charges,total_amount,cash,change,payment_type,emp_id)values(?,?,?,?,?,?,?,?,?)";
preparedStatement.setString(1, "Test");
preparedStatement.setInt(1, 44);
// repeat the above two based on your requirement and datbase field
pst=conn.prepareStatement(sql0);
pst.execute();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.