Im having troubles converting my String to integer. My Data Table consist of 3 columns, two of which are INT type. But when i started inserting my String to my Database it gives an Auto_Increment error:
Class:
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);
}
}
);
}
My 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);
}
This is actually a follow up regarding my previous question. My Question is that how can i convert my String to Integer and then insert it on my Database? If you might ask i got my String from my jTable which then got it from my database. What i want to do now is that get the values inside that jTable and insert it to a new Database.
You can convert a String to an Integer by using the Integer.toString()
method. Just pass the string in as the parameter.
Try to cast object to string as below
String a = String.valueOf(jTable1.getValueAt(selectedRow, 0));
pst.setString(1, a);
In case Your target field type is integer do this.
pst.setInt(1,Integer.ParseInt(a));
By assuming that your auto_increment field is you primary key and you're trying to put the first value there, it is better try this.
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");
Note :- For auto increment fields in databases, you don't need to add a value in inserting. That is why it is called auto_increment. So I removed first field so the second field became your first prepared statement parameter.
Hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.