am trying to edit and update jtable cells as in my code below. my problem is that a single row when updated all the other rows get the same values. i mean only one row is updated and all other a duplicated. can any one help with a good approach. thanks
int count = Table_purchase.getRowCount();
int col = Table_purchase.getColumnCount();
String pod_id[] = new String[count];
String po_id[] = new String[count];
String order_qty[] = new String[count];
String item_id[] = new String[count];
String unit_price[] = new String[count];
String recived_qty[] = new String[count];
String rejected_qty[] = new String[count];
for (int i = 0; i < count; i++) {
po_id[i] = Table_purchase.getValueAt(i,0).toString();
pod_id[i] = Table_purchase.getValueAt(i,1).toString();
order_qty[i] = Table_purchase.getValueAt(i,2).toString();
item_id[i] = Table_purchase.getValueAt(i,3).toString();
unit_price[i] = Table_purchase.getValueAt(i,4).toString();
recived_qty[i] = Table_purchase.getValueAt(i, 5).toString();
rejected_qty[i] = Table_purchase.getValueAt(i,6).toString();
try {
String sql = "update purchase.purchase_detail set pod_id='" + pod_id[i] + "',order_qty='" + order_qty[i] + "',item_id='" + item_id[i] + "', unit_price='" + unit_price[i] + "', recived_qty='" + recived_qty[i] + "',rejected_qty='" + rejected_qty[i] + "'where po_id= '" + po_id[i] + "'";
pst = conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "updated");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Your sql statement does not contain a where-clause, hence all rows in the database table are updated for each iteration of the swing-table-rows, and in the end, all the database-rows will have the values from the last swing-table-row.
(And, use pst.setParameter (http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html) and do not mix sql into gui-code.)
Related
I am trying to make a program in which i read an input from the user i.e. in the textfield named gname and store its value to a string called grammar. Now this input is what sorts my output from the database.
Database looks like this
So when user enters G1 in the textfield it should display records in such a way
A->ab,A-ab,B->b
But it only shows 1st element when i use if(myRs.next) and last one if i use while(myRs.next().
current output is
Here is the code for this:
its all in try catch block
String grammar = gname.getText();
myCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/grammar", "root", "");
JOptionPane.showMessageDialog(rootPane, "Connected to database");
mystmt = myCon.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String query = "SELECT starting_symbol, value from starting_symbol where grammar= '" + grammar + "'";
String query2 = "SELECT non_terminals, terminals from input_values where grammar= '" + grammar + "'";
mystmt.addBatch(query);
mystmt.addBatch(query2);
myCon.setAutoCommit(false);
mystmt.addBatch(query);
mystmt.addBatch(query2);
myRs = mystmt.executeQuery(query);
while (myRs.next()) {
String s = myRs.getString("starting_symbol");
String val = myRs.getString("value");
output.setText(s + "-> " + val);
}
myRs = mystmt.executeQuery(query2);
ArrayList<String> list_one = new ArrayList<String>();
ArrayList<String> list_two = new ArrayList<String>();
while (myRs.next()) {
list_one.add(myRs.getString("non_terminals"));
list_two.add(myRs.getString("terminals"));
for (int i = 0; i < list_one.size(); i++) {
output_2.setText(list_one.get(i) + "->" + list_two.get(i));
}
}
Please help me in getting the correct outut
Use StringBuilder Luke
StringBuilder b = new StringBuilder();
while (myRs.next()) {
String s = myRs.getString("starting_symbol");
String val = myRs.getString("value");
if (b.length() > 0) {
b.append(',');
}
b.append(s + "-> " + val);
}
output.setText(b.toString());
And do the same for output_2 field
Your code snippet can be just like the following:
StringBuilder sb = new StringBuilder();
while (myRs.next()) {
if (sb.length() > 0) sb.append(",");
sb.append(myRs.getString("non_terminals"))
.append("->")
.append(myRs.getString("terminals"));
}
Instead of calling output_2.setText multiple times that only set the text to be the last fetch value of non_terminals -> terminals in this case B->b.
Connection conn = SqlConnection.getConnection("jdbc:mysql://localhost:3306/stocks");
Statement statement = conn.createStatement();
File path = new File("/Users/Zack/Desktop/JavaDB/BALANCESHEETS");
for(File file: path.listFiles()) {
if (file.isFile()) {
String fileName = file.getName();
String ticker = fileName.split("\\_")[0];
if (ticker.equals("ASB") || ticker.equals("FRC")) {
if (ticker.equals("ASB")) {
ticker = ticker + "PRD";
}
if (ticker.equals("FRC")) {
ticker = ticker + "PRD";
}
}
//CSVReader reader = new CSVReader(new FileReader(file));
//List entries = reader.readAll();
//ArrayList<String> entry = new ArrayList<String>();
Reader reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
int c;
while ((c = reader.read()) != -1) {
builder.append((char) c);
}
String string = builder.toString();
ArrayList<String> stringResult = new ArrayList<String>();
if (string != null) {
String[] splitData = string.split("\\s*,\\s*|\\n");
for (int i = 0; i <splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() ==0)) {
stringResult.add(splitData[i].trim());
}
}
}
String columnName = null;
int yearCount = 0;
for (int i = 0; i < stringResult.size(); i++) {
int sL = stringResult.get(i).length();
for (int x = 0; x < sL; x++) {
if (Character.isLetter(stringResult.get(i).charAt(x))) {
yearCount = 0;
System.out.println("index: " + i);
columnName = stringResult.get(i);
columnName = columnName.replace(" ", "_");
System.out.println(columnName);
i++;
break;
}
}
yearCount++;
String value = stringResult.get(i);
System.out.println("Year: " + stringResult.get(yearCount) + " Value: " + value + " Stock: " + ticker + " Column: " + columnName );
if (!(columnName == null)) {
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUE ('" + ticker + "','" + stringResult.get(yearCount) + "','" + value + "')";
String writeValues2 = "UPDATE BalanceSheet "
+ "SET ticker = '" + ticker + "', "
+ "Year = '" + stringResult.get(yearCount) + "', "
+ columnName + " = '" + value + "' "
+ "WHERE ticker = '" + ticker + "'";
statement.executeUpdate(writeValues2);
}
}
Towards the bottom of the code are two queries I tried, I'm trying to get all data organized by ticker and year into a table, "writeColumns" works but it's making a new row for every new "value" put into "columnName". My second attempt "writeColumns2" doesn't do anything.
I want to update the same row with a certain year for all values and then move onto the next year, then next ticker.
If I have understood your question correctly, you want to insert a row if it doesn't exists but update the values if it already does. You need to use ON DUPLICATE KEY UPDATE
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUES (?,?,?) "
+"ON DUPLICATE KEY UPDATE " + columnName +"=?";
Statement statement = conn.prepareStatement(writeValues);
statement.setString(1,ticker);
statement.setString(2,stringResult.get(yearCount));
statement.setString(3, value);
This will solve your immidiate problem provided you create a UNIQUE index on ticker,year
However there are lot's of other issues here.
An update for each column - Currently you are doing an insert/update for each column on the table. What you are supposed to do is to insert update all the columns at one.
You are not using prepared statements addressed in my code sample
You shouldn't be doing this at all the best way to batch process data is to use MYSQL's built in LOAD DATA INFILE command. If your data is not in a format that can be easily imported into mysql, what your Java code can do is to transform it into a format that can be. Such a code will be a lot simpler and neater than what you have now
I use JDBC to get data from sqlite data base. In DB I have 3 column - login, password and role. I try find row by login, but it doesn't work , and I have exeption when I try getString("password") or "role", where is the mistake? Thanks
resSet = statmt.executeQuery("SELECT * FROM users WHERE login='"+login+"';");
if( hasUser( login)){
System.out.println("User finded:");
while(resSet.next()) {
System.out.println("login = " + resSet.getString("login"));
// !exeption
System.out.println("password = " + resSet.getString("password"));
// !exeption
System.out.println("role = " + resSet.getString("role"));
System.out.println();
}
}else{
System.out.println( "User not found");
}
You can check to see what column names are being returned.
ResultSetMetaData rsmd = resSet.getMetaData();
int colCount = rsmd.getColumnCount();
String rValue = "";
for (int i = 1; i <= colCount ; i++){
String name = rsmd.getColumnName(i);
rValue += name + " ";
}
System.out.println(rValue);
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount(); //number of column
String columnName[] = new String[count];
for (int i = 1; i <= count; i++)
{
metaData.getColumnLabel(i));
}
Refer to this ans..ans see what are the names of your columns in resultant set
http://stackoverflow.com/questions/19094999/java-how-to-get-column-name-on-result-set
I am actually building a project where the names of tables present in databases of mysql are displayed in a list in java.
user selects a table from a list and the description of that table in given using "desc tablename" command.
The problem is, it is supposed to get every field in table but it only gets first field. Below i have explained it more, but first heres my code-:
try {
int rowCount = tableModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
tableModel.removeRow(i);
}
String z = jList2.getSelectedValue().toString();
try {
Class.forName("java.sql.DriverManager");
} catch (ClassNotFoundException e) {
timeget();
jTextArea4.append(now + ": " + "/ Failed in getting Driver \n Error Message: " + e.getMessage() + " / \n \n");
JOptionPane.showMessageDialog(this, e.getMessage());
}
DriverManager.getConnection("jdbc:mysql://localhost:" + GlobalParams.portvar + "/", "" + k, "" + j);
stmnt = (Statement) con.createStatement();
String query = "desc " + z;
jTextArea5.append(now + ": " + "/ desc " + z + "; / \n \n");
ResultSet rs = stmnt.executeQuery(query);
String[] cnames = {"Field", "Type", "Null", "Key", "Extra"};
tableModel.setColumnIdentifiers(cnames);
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
jTable1.setFillsViewportHeight(true);
if (rs.next()) {
String field = rs.getString("Field");
String type = rs.getString("type");
String nullinfo = rs.getString("null");
String key = rs.getString("key");
String extra = rs.getString("extra");
tableModel.addRow(new Object[]{field, type, nullinfo, key, extra});
}
catch(SQLException e){//some blabla}
Now for detailing into problem->
Say from the list, i select a table called "city". Originally, it has four fields- ID, Name, Population, CountryCode. But in my jTable, only "ID" appears.
the code...
int rowCount = tableModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
tableModel.removeRow(i);
}
...is simply to remove fields of old table when a new table is selected from list.
Hope i clarified my prob.
Please help regarding this. Thanks.
the problem is in this
if (rs.next()) {
String field = rs.getString("Field");
String type = rs.getString("type");
String nullinfo = rs.getString("null");
String key = rs.getString("key");
String extra = rs.getString("extra");
tableModel.addRow(new Object[]{field, type, nullinfo, key, extra});
}
you are not continuing the loop
change the if loop to while loop
while(rs.next()) {
String field = rs.getString("Field");
String type = rs.getString("type");
String nullinfo = rs.getString("null");
String key = rs.getString("key");
String extra = rs.getString("extra");
tableModel.addRow(new Object[]{field, type, nullinfo, key, extra});
}
every time this starts my program freezes, and I can't figure out why.
It doesn't give any errors, it just freezes.
Is it possible I've created some kind of endless loop?
public static String[] DataVoorList(int coureur) throws SQLException{
ArrayList datalijst = new ArrayList();
String query = ""
+ "SELECT rd_datum, rd_locatie, rd_code "
+ "FROM racedag WHERE rd_code in( "
+ "SELECT i_rd_code "
+ "FROM inschrijvingen "
+ "WHERE i_c_nummer = " + coureur + ");";
ResultSet rs = Database.executeSelectQuery(query);
int i=0;
while (rs.next()){
String datum = rs.getString("rd_datum");
String locatie = rs.getString("rd_locatie");
String totaal = "" + datum + " - " + locatie;
datalijst.add(i, totaal);
i++;
int codeInt = rs.getInt("rd_code");
String code = ""+codeInt;
datalijst.add(i, code);
i++;
}
return Race.StringDataVoorList(datalijst);
}
public static String[] StringDataVoorList(ArrayList invoer){
int lengte = invoer.size();
String[] uitvoer = new String[lengte];
int i =0;
while (i < uitvoer.length){
uitvoer[i] = ""+invoer.get(i);
}
return uitvoer;
}
EDIT: I've solved the increment. However, it still freezes.
EDIT 2: I think I have located the problem (but I can be wrong)
public static String[] DataVoorList(int coureur) throws SQLException {
System.out.println("stap 1");
ArrayList datalijst = new ArrayList();
String query = ""
+ "SELECT rd_datum, rd_locatie, rd_code "
+ "FROM racedag WHERE rd_code in( "
+ "SELECT i_rd_code "
+ "FROM Inschrijvingen "
+ "WHERE i_c_nummer = " + coureur + ");";
ResultSet rs = Database.executeSelectQuery(query);
System.out.println("stap 2");
int i = 0;
while (rs.next()) {
String datum = rs.getString("rd_datum");
String locatie = rs.getString("rd_locatie");
String totaal = "" + datum + " - " + locatie;
datalijst.add(i, totaal);
System.out.println("stap 3");
i++;
int codeInt = rs.getInt("rd_code");
String code = "" + codeInt;
datalijst.add(i, code);
i++;
System.out.println("stap 4");
}
return Race.StringDataVoorList(datalijst);
(I've changed the while loop to a for loop)
public static String[] StringDataVoorList(ArrayList invoer) {
int lengte = invoer.size();
String[] uitvoer = new String[lengte];
for (int i = 0; i < uitvoer.length; i++) {
uitvoer[i] = "" + invoer.get(i);
}
return uitvoer;
}
}
this is being called from here:
public MijnRacedagenScherm() throws SQLException{
initComponents();
int gebruiker = Inloggen.getNummer();
String[] DataVoorList = Race.DataVoorList(2);
int lengte = DataVoorList.length;
System.out.println("resultaat is " + DataVoorList[0]);
int i = 0;
while (i < lengte) {
ListRacedagenCoureur.setListData(DataVoorList);
i = i + 2;
}
System.out.println("lengte is " + lengte);
}
This is a new screen, but in the previous screen I get a unreported SQL exception over this:
private void ButtonZienRacedagActionPerformed(java.awt.event.ActionEvent evt) {
new MijnRacedagenScherm().setVisible(true);
}
Well, um... In this section:
while (i < uitvoer.length){
uitvoer[i] = ""+invoer.get(i);
}
Where is i incremented?
Indeed it is, this
int i =0;
while (i < uitvoer.length){
uitvoer[i] = ""+invoer.get(i);
}
You never increment i.
As stated problem is in your while loop.
for loop is more suitable for iterating over indexed data type
for (int i = 0; i < uitvoer.length; i++) {
uitvoer[i] = ""+invoer.get(i);
}
How many rows are you processing? The way you append strings is quite slow, maybe it's not freezing anymore but just taking a long time to complete.