[英]Incorrect Integer Value: How do i convert my Data from String to Int to avoid Auto_Increment?
我在将我的String转换为整数时遇到麻烦。 我的数据表由3列组成,其中两列是INT类型。 但是,当我开始将String插入数据库时,会出现Auto_Increment错误:
类:
public class Strong extends javax.swing.JFrame {
String a;
public Apply() {
initComponents();
jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent e)
{
int selectedRow = jTable1.getSelectedRow();
a = (String) jTable1.getValueAt(selectedRow, 0);
}
}
);
}
我的executeUpdate:
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/application","root","");
String sql= "insert into Mycart values(?,?,?)";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, (String)a);
pst.setString(2, (String)a);
pst.setString(3, (String)a);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Added to Cart");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
这实际上是关于我之前的问题的跟进。 我的问题是,如何将我的String转换为Integer,然后将其插入数据库? 如果您可能要问,我从jTable中获取了String,然后从数据库中获取了它。 我现在要做的是获取jTable中的值,并将其插入到新数据库中。
您可以使用Integer.toString()
方法将String转换为Integer。 只需将字符串作为参数传递即可。
尝试将对象强制转换为字符串,如下所示
String a = String.valueOf(jTable1.getValueAt(selectedRow, 0));
pst.setString(1, a);
如果您的目标字段类型是整数,请执行此操作。
pst.setInt(1,Integer.ParseInt(a));
通过假设您的auto_increment字段是主键,并尝试将第一个值放在那里,最好尝试一下。
String sql= "insert into Mycart (your_string_field, your_int_field) values(?,?)";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, "your_data_goes_here"); // for string
pst.p.setInt(2, Integer.parseInt("your_data_goes here")); // for integer
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Added to Cart");
注意:-对于数据库中的自动增量字段,您无需在插入时添加值。 这就是为什么将其称为auto_increment。 因此,我删除了第一个字段,因此第二个字段成为您的第一个准备好的语句参数。
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.