how to correctly MySQL "desc table" via java connectivity - java

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});
}

Related

How to travel the rows of sql table using index in java

I have two DB and I want to transfer data from DB A tables to DB B tables. All tables from both DB have same syntax. I have this method that takes an argument name of the table. First for loop will travel the columns and I need another for or something else that travels the rows of that specific column. That switch-case retrieve the specific datatype from table column and store it into a field and after I use that field to insert the value in the same place in the DB B. Please some suggestion? I let my trash code below:
public void getAndInsertData(String nameOfTable) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con1 = DriverManager.getConnection(urlDB1, user1, password1);
Statement s1 = con1.createStatement();
Connection con2 = DriverManager.getConnection(urlDB2, user2, password2);
Statement s2 = con2.createStatement();
ResultSet rs1 = s1.executeQuery("SELECT * FROM " + nameOfTable);
ResultSetMetaData rsmd1 = rs1.getMetaData();
int columnCount = rsmd1.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
String columnName = rsmd1.getColumnName(column);
int columnType = rsmd1.getColumnType(column);
// for (int row = 1; row <= nrRows; row++) {
switch (columnType) {
case 4:
int integerValue = rs1.getInt(row);
String integerQuery = "insert into " + nameOfTable + " (" + columnName + ") VALUES(" + integerValue
+ ");";
s2.executeUpdate(integerQuery);
s2.close();
break;
case 12:
String varcharValue = rs1.getString(row);
String varcharQuery = "insert into " + nameOfTable + " (" + columnName + ") VALUES(" + varcharValue
+ ");";
s2.executeUpdate(varcharQuery);
s2.close();
default:
System.out.println("Default");
break;
}
}
// }
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Transfer done...");
}
}

Java and SQL: ResultSetMetaData and ResultSet

I really need help. I am trying to retrieve a data from in my database using ResultSetMetaData and ResultSet. Also I am using a stored Procedure. The program is run find, however when I run it and be expecting 3 result from the row, instead it will give me 2. For example if I ask a user to enter a position and there are 6 player in that position, it will give me 5 players instead of 6 player.
Here is my code
if (!rs.next()) {
System.out.println("There is no match in the database " + position);
}
else {
System.out.println(String.format(" " + " %-19s %s", "Name",
"Rank") + "\t" + String.format("%-11s %s", "Position",
"School") + "\t" + String.format("%-6s %s",
"Age", "War") + "\n-----------------"
+ "-------------------------------------------------");
while (rs.next()) {
int rank = 0, age = 0;
String name = null, pos = null, sch = null;
double war = 0;
for (int i = 1; i < colum - 1; i++) {
rank = rs.getInt(1);
name = rs.getString(2);
pos = rs.getString(3);
sch = rs.getString(4);
age = rs.getInt(5);
war = rs.getDouble(6);
}
When I run my java code I get this result. It's not getting the first index in the list
When I call my stored procedure in MYSQL Workbench, I get this result
You have read first index in
if (!rs.next()) {
itself. This will move the cursor to the next row. You will have to remove this and it will give all the rows.

Before start of result set running multiple sql

I'm currently working on an application for a restaurant. The idea for the code I'm currently working on is that it gets the name from a combobox and inserts a receipt into the database whith the employee number of the person who is working on it. The code whith which I'm trying to do it is:
RestaurantOrder sqlRestaurantOrder = new RestaurantOrder();
ActionListener printReceiptListner;
printReceiptListner = (ActionEvent) -> {
int ID = Integer.parseInt(input1.getText());
try {
SystemManager manager = new SystemManager();
ResultSet rs = manager.stmt.executeQuery(sqlRestaurantOrder.setIdSql(ID));
while (rs.next()) {
double totalPrice = rs.getDouble("sumprice");
if (ID > 0) {
Receipt receiptSql = new Receipt();
String firstName = (String) cb.getSelectedItem();
String checkoutDate = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
ResultSet rs2 = manager.stmt.executeQuery(receiptSql.getEmployeeId(firstName));
int employeeId = rs2.getInt("id");
while (rs2.next()) {
Receipt receiptSql2 = new Receipt();
ResultSet rs3 = manager.stmt.executeQuery(receiptSql2.SetStatusReceipt(employeeId, checkoutDate, ID, totalPrice));
while (rs3.next()) {
}
}
}
}
} catch (SQLException k) {
JOptionPane.showMessageDialog(null, k.getMessage());
}
};
The statements are:
public class Receipt {
public String sql;
public String sql2;
public String getEmployeeId(String firstName){
return sql2 = "SELECT id FROM employee WHERE firstName = '" + firstName + "';";
}
public String SetStatusReceipt(int employeeId, String checkoutDate, int id, double totalPrice){
return sql = "INSERT INTO `receipt` (`employeeId`, `price`, `restaurantOrderId`, `checkoutDate`) VALUES (" + employeeId + " , " + totalPrice + ", " + id + ", " + checkoutDate + ");";
};
}
I'm getting the error before start of result set which I looked up what it means but I can't get it fixed at the moment. Help will be appreciated.
If I forgot to post more important code let me know I'll update it
You have to call ResultSet.next() before you are able to access the fields of that ResultSet. So you need to move your assignment of employeeId into your while loop:
while (rs2.next()) {
int employeeId = rs2.getInt("id");
From the documentation of ResultSet.next():
A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

how to edit/update jtable cell values into database

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.)

MySQL command SELECT values in column - JDBC

I'm using MySQL commands via JDBC (Java) to make changes to my database. I have implemented the following method to return the values of a column. The goal is to have the location in the column (row) correspond with their location in the array (index). This works with String columns, but with numerical columns, the ResultSet seems to place them in ascending order, thus making their positioning in the returned String array not reflect their positioning in the column. 'rs' is a ResultSet reference variable.
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName;
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}
It's as simple as adding an ORDER BY clause to the SQL command. Here's my working method:
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName + " ORDER BY " + columnName1 + " ASC, " + columnName2 + " ASC";
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}

Categories