我在Java中有一个表,其中包含几行,但是当我保存数据时,仅保存了最后一行,其余的未保存。
下面是我的代码:
try {
int rows=jTable1.getRowCount();
for (int row = 0; row < rows; row++) {
String qtys = (String) jTable1.getValueAt(row, 0);
String name = (String) jTable1.getValueAt(row, 1);
String commo = (String) jTable1.getValueAt(row, 2);
String wei = (String) jTable1.getValueAt(row, 3);
String queryco = "Insert into invoice(qtys,name,commo,wei) " +
"values ('"+qtys +"','"+name+"','"+commo+"','"+wei+"')";
pst = conn.prepareStatement(queryco);
pst.execute();
}
JOptionPane.showMessageDialog(null, "Successfully Save");
}
catch (Exception e) {
JOptionPane.showMessageDialog(this,e.getMessage());
}
答案 0 :(得分:0)
package com.sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class JTableExample {
JFrame f;
// Table
JTable j;
void process() throws Exception
{
// Frame initiallization
f = new JFrame();
// Frame Title
f.setTitle("JTable Example");
// Initializing the JTable
j = new JTable();
j.setBounds(30, 40, 200, 300);
DefaultTableModel dtm = new DefaultTableModel(0, 0);
// add header of the table
String header[] = new String[] { "Prority", "Task Title", "Start",
};
// add header in table model
dtm.setColumnIdentifiers(header);
for (int count = 1; count <= 1000; count++) {
dtm.addRow(new Object[] { "data"+count, "data"+count, "data"+count});
}
j.setModel(dtm);
// adding it to JScrollPane
JScrollPane sp = new JScrollPane(j);
f.add(sp);
// Frame Size
f.setSize(500, 200);
// Frame Visible = true
f.setVisible(true);
int rows=j.getRowCount();
Class.forName("com.mysql.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila",
"root","root");
String sqlQuery = "Insert into sakila.student(name,dep,rollnumber)
values(?,?,?)";
PreparedStatement stmt = connection.prepareStatement(sqlQuery);
try {
for(int row = 0; row<rows; row++)
{
System.out.println("Count:"+row);
stmt.clearParameters();
String name= (String) j.getValueAt(row, 0);
String rollNumber = (String) j.getValueAt(row, 1);
String dep = (String) j.getValueAt(row, 2);
stmt.setString(1, name);
stmt.setString(2, dep);
stmt.setString(3, rollNumber);
stmt.executeUpdate();
}
} catch(Exception e) {
System.out.println(e.getMessage());
}
connection.close();
}
// Driver method
public static void main(String[] args) throws Exception
{
JTableExample jt = new JTableExample();
jt.process();
} }
我已使用此代码在其中可以将5000行存储到数据库而没有任何问题。所有数据都已成功存储在数据库中。