How to not duplicate when adding data in JTable because when I am adding in JTable it always duplicate the same data.
public void buyproduct() {
String name = code_cart1.getText();
try {
con = Connector.getConnection();
PreparedStatement pst = con.prepareStatement("SELECT `Code`, `Category`, `ProductName`, `Size`, `Quantity`, `Price`, `Sub-Total` FROM `product_table` WHERE Code = ?");
pst.setString(1, name);
rs = pst.executeQuery();
while (rs.next()) {
int currentqty = rs.getInt("Quantity");
int pricenew = Integer.parseInt(price_cart1.getText());
int qtynew = Integer.parseInt(quantity_cart1.getText());
int tot = pricenew * qtynew;
if (qtynew > currentqty || qtynew == 0) {
JOptionPane.showMessageDialog(this, "Out of Stock!");
} else {
DefaultTableModel model = (DefaultTableModel) cart_Display.getModel();
model.addRow(new Object[]{code_cart1.getText(),
category_cart1.getText(),
productname_cart1.getText(),
size_cart1.getText(),
quantity_cart1.getText(),
price_cart1.getText(),
tot});
int sum = 0;
for (int i = 0; i < cart_Display.getRowCount(); i++) {
sum = sum + Integer.parseInt(cart_Display.getValueAt(i, 6).toString());
}
SubTotal_Cart_text.setText(Integer.toString(sum));
SubTotal_Cart_text1.setText(Integer.toString(sum));
code_cart1.setText("");
category_cart1.setText("");
productname_cart1.setText("");
size_cart1.setText("");
quantity_cart1.setText("");
price_cart1.setText("");
}
}
} catch(Exception ex) {
}
}
Related
I'm making a GUI and it includes a JPanel, inside that JPanel there's a JTable, and what I want to do is: when I click a button, both of them appear (since I'm using CardLayout). Code:
private void teGjithaButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
parentPanel.setVisible(true);
parentPanel.removeAll();
parentPanel.add(tgjPanel);
parentPanel.repaint();
parentPanel.revalidate();
listAllCurtains();
} catch (SQLException ex) {
Logger.getLogger(MainBrillant.class.getName()).log(Level.SEVERE, null, ex);
}
}
And the code for listAllCurtains():
DefaultTableModel deftm = (DefaultTableModel) allTable.getModel();
if (deftm.getRowCount() != 0) {
deftm.setRowCount(0);
}
stm = (Statement) conn.createStatement();
ResultSet rs = stm.executeQuery("select * from customerregister.curtain inner join curtainrel on curtain.code = curtainrel.curtainCode;");
while (rs.next()) {
String shifra = rs.getString("code");
String ngjyra = rs.getString("color");
String emri = rs.getString("name");
double cmimi = rs.getDouble("price");
double sasia = rs.getDouble("amount");
allCurtains.add(new Curtain(shifra, ngjyra, emri, cmimi, sasia));
}
Object[] row = new Object[5];
for (int i = 0; i < allCurtains.size(); i++) {
row[0] = allCurtains.get(i).getShifra();
row[1] = allCurtains.get(i).getEmri();
row[2] = allCurtains.get(i).getNgjyra();
row[3] = allCurtains.get(i).getCmimi();
row[4] = allCurtains.get(i).getSasia();
deftm.addRow(row);
}
}
The problem is that when i re-click the button, eventhough there's this part of the code to ensure the data is not duplicated:
if (deftm.getRowCount() != 0) {
deftm.setRowCount(0);
}
It still continues to insert the same data into table each time the button is clicked. I can't figure out why this is happening, and I'd really appreciate your help.
Perhaps you should Clear your JTable model of its rows before you decide to reissue the data again. Instead of your:
if (deftm.getRowCount() != 0) {
deftm.setRowCount(0);
}
code, perhaps use a simple clearTable() method like:
private void clearJTable(DefaultTableModel yourTableModel) {
while (yourTableModel.getRowCount() > 0) {
for (int i = 0; i < yourTableModel.getRowCount(); i++) {
yourTableModel.removeRow(i);
}
}
}
and then in your code:
DefaultTableModel deftm = (DefaultTableModel) allTable.getModel();
clearJTable(deftm);
stm = (Statement) conn.createStatement();
ResultSet rs = stm.executeQuery("select * from customerregister.curtain inner join curtainrel on curtain.code = curtainrel.curtainCode;");
while (rs.next()) {
String shifra = rs.getString("code");
String ngjyra = rs.getString("color");
String emri = rs.getString("name");
double cmimi = rs.getDouble("price");
....................................
....................................
....................................
currently I have data in MySQL server and I am calling the datas onto the JTable through JDBC. However there are 1369 rows and it seems that it has too much data for it to load. It usually takes 5 minutes to load. Are there anyways to optimize the process? This is my code(I apologize in advance for a messy code):
public class DataTable {
private String databaseName = "*****";
private String tableName = "******";
public void showDatabase(){
Connection conn = null;
DatabaseMetaData meta = null;
Statement stmt = null;
ResultSet rs = null;
int k = 0;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/" + databaseName;
String connectionUser = "*****";
String connectionPassword = "*****";
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
meta = conn.getMetaData();
dataSets(stmt, meta);
}catch(Exception e){
e.printStackTrace();
} finally{
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
//return the column size of the table
public int getColumnNumber(DatabaseMetaData meta, Statement stmt) throws SQLException
{
//ResultSet rs = meta.getColumns(null, null, "practiceexample", null);
ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
return columnsNumber;
}
//return the rowNumber of the tables
public int getRowNumber(Statement stmt) throws SQLException
{
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
int rowCount = 0;
while(rs.next()){
rowCount = rs.getInt(1);
}
return rowCount;
}
public void dataSets(Statement stmt, DatabaseMetaData meta) throws SQLException
{
String[] columnNames = new String[getColumnNumber(meta, stmt)];
String[][] dataSets = new String[getRowNumber(stmt)][columnNames.length];
ResultSet column = meta.getColumns(null, null, tableName, null);
int i = 0;
while(column.next())
{
columnNames[i] = column.getString("COLUMN_NAME");
//columnNames.add(i, column.getString("COLUMN_NAME"));
i++;
}
for(int j = 0; j < dataSets.length; j++)
{
String[] singleRowData = new String[columnNames.length];
ResultSet data = null;
for(int k = 0; k < columnNames.length; k++)
{
String columnName = columnNames[k];
data = stmt.executeQuery("SELECT " + columnName +
" FROM " + tableName + " LIMIT " + j + ", " + 1);
while(data.next())
{
singleRowData[k] = data.getString(columnName);
}
}
dataSets[j] = singleRowData;
}
SimpleTable table = new SimpleTable(columnNames, dataSets);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
table.createAndShowGUI();
}
});
}
class SimpleTable{
String[] columns;
String[][] dataSets;
public SimpleTable(String[] columns, String[][] dataSets){
this.columns = columns;
this.dataSets = dataSets;
}
public void createAndShowGUI(){
JPanel gui = new JPanel(new BorderLayout(3, 3));
final JTable table = new JTable(new DefaultTableModel(dataSets, columns));
final JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
Dimension dimension = table.getPreferredSize();
scrollPane.setPreferredSize(new Dimension(dimension.width, table.getRowHeight() * 30));
JPanel navigation = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton next = new JButton(">");
next.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
int height = table.getRowHeight() * (20-1);
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setValue(bar.getValue() + height);
}
});
JButton previous = new JButton("<");
previous.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int height = table.getRowHeight()*(20-1);
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setValue( bar.getValue()-height );
}
} );
navigation.add(previous);
navigation.add(next);
gui.add(scrollPane, BorderLayout.CENTER);
gui.add(navigation, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null, gui);
}
}
}
IMHO the root of the bad permormance is you unnecessarily query the database mutliple times to get the data (columns, rows, rows number, columns number, etc) you need:
To get columns number:
ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName);
To get rows number:
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
To get rows (this is the worst beacuse it's inside a loop):
data = stmt.executeQuery("SELECT " + columnName + " FROM " + tableName + " LIMIT " + j + ", " + 1);
How to solve it
Just query the database once. A single ResultSet and its associated ResultSetMetaData should be enough to accomplish your goal. Additionaly, and as already suggested, use a SwingWorker to do database calls in a separate thread. For example:
final JTable table = new JTable();
SwingWorker<Void, TableModel> worker = new SwingWorker<Void, TableModel> () {
#Override
protected Void doInBackground() throws Exception {
ResultSet resultSet = stmt.executeQuery("SELECT * FROM " + tableName);
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount(); // columns number
String[] columnNames = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
columnNames[i] = metaData.getColumnName(i); // fill columns names
}
resultSet.last();
int rowCount = resultSet.getRow(); // get rows number
resultSet.beforeFirst();
Object[][] data = new Object[rowCount][columnCount];
int currentRow = 0;
while (resultSet.next()) {
for (int currentColumn = 1; currentColumn <= columnCount; currentColumn++) {
data[currentRow][currentColumn - 1] = resultSet.getObject(currentColumn); // fill data set
}
currentRow++;
}
TableModel model = new DefaultTableModel(data, columnNames);
publish(model);
return null;
}
#Override
protected void process(List<TableModel> chunks) {
TableModel model = chunks.get(0);
table.setModel(model);
}
}
worker.execute();
Hello I would like to print data from mysql query to my Jtable, I knw how to print the conventional data(String), but do not know how to do it with pictures. What I need is print the picture in the first cell of the table.
public void SearchMovie() throws SQLException {
try {
Connection con = null;
ResultSet rs = null;
Statement st = null;
String Genre = ComboGenero.getSelectedItem().toString();
String Era = ComboEra.getSelectedItem().toString();
String Clsssification = ComboClasification.getSelectedItem().toString();
String sql = "select Foto,Title,Year,Country ,Rating from movie where Genre ='" + Genre + "'";
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/whichmovie", "Asis", "dekrayat24");
st = con.createStatement();
rs = st.executeQuery(sql);
DefaultTableModel model = new DefaultTableModel();
this.jTable1.setModel(model);
jTable1.setDefaultRenderer(Object.class,new IconCellRenderer());
jTable1.setRowHeight(40);
ResultSetMetaData rsMD = rs.getMetaData();
int numcolumnas = rsMD.getColumnCount();
for (int x = 1; x <= numcolumnas; x++) {
model.addColumn(rsMD.getColumnLabel(x));
}
while (rs.next()) {
Object[] fila = new Object[numcolumnas];
for (int i = 0; i < numcolumnas; i++) {
fila[i] = rs.getObject(i + 1);
ResultadosLabel.setText(numcolumnas + "Movies found");
}
model.addRow(fila);
}
rs.close();
st.close();
con.close();
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
Thanks .
I need to fetch data from multiple tables and export into excel sheet for each table. I don't want to use the getXXX() method as there are large number of columns and I don’t know the data type of each column. I need to fetch an entire row and store in the result in List.
I fetched each column using getObject() and also the class type using MetaData.getColumnClassName().
For example
Object val = resultSet.getObject(i);
I try to cast this val to its actual type using getColumnClassName() but it gives me an error while casting.
Can anyone please help me.
public class Row {
public Map<Object, Class> row;
public static Map<String, Class> TYPE;
static {
TYPE = new HashMap<String, Class>();
TYPE.put("INTEGER", Integer.class);
TYPE.put("NUMERIC", BigDecimal.class);
TYPE.put("DOUBLE", Double.class);
TYPE.put("VARCHAR2", String.class);
}
public Row() {
row = new HashMap<Object, Class>();
}
public <t> void add(t data) {
row.put(data, data.getClass());
}
public void add(Object data, String sqlType) {
add((Row.TYPE.get(sqlType)) data);
}
public static void formTable(ResultSet rs, List<Row> table) throws SQLException {
if(rs == null)
return;
ResultSetMetaData rsmd = rs.getMetaData();
int colCt = rsmd.getColumnCount();
while(rs.next()) {
Row row = new Row();
for(int i = 0; i < colCt; i++) {
row.add(rs.getObject(i), rsmd.getColumnTypeName(i));
}
table.add(row);
}
}
public static void main(String[] args) {
}
}
Try this code:
Connection connection = DriverManager.getConnection("URL", "USERNAME", "PASSWORD");
PreparedStatement statement = connection.prepareStatement("select * from table");
ResultSet resultSet = statement.executeQuery();
if (resultSet != null) {
while (resultSet.next()) {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
int type = resultSetMetaData.getColumnType(i);
if (type == Types.VARCHAR || type == Types.CHAR) {
System.out.println(resultSet.getString(i));
} else {
System.out.println(resultSet.getLong(i));
}
}
System.out.println("-----------");
}
}
You should extend it with other datatypes.
Step 1: get the metadata
ResultSetMetaData rsmd;
rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
int[] columnsType = new int[numColumns + 1];
columnsType[0] = 0;
for (int i = 1; i <= numColumns; i++)
columnsType[i] = rsmd.getColumnType(i);
Step 2: fetch a row at a time from the result set and check the data type
String s;
Object o;
while (rs.next()) {
for (int i = 1; i <= numColumns; i++) {
if (columnsType[i] == java.sql.Types.NUMERIC || columnsType[i] == java.sql.Types.CHAR || columnsType[i] == java.sql.Types.VARCHAR) {
s = rs.getString(i);
} else if (columnsType[i] == java.sql.Types.NVARCHAR) {
s = rs.getNString(i);
} else if (columnsType[i] == java.sql.Types.BOOLEAN) {
// TODO
} else if (columnsType[i] == java.sql.Types.FLOAT || columnsType[i] == java.sql.Types.DOUBLE) {
// TODO
} else if (columnsType[i] == java.sql.Types.TINYINT || columnsType[i] == java.sql.Types.SMALLINT || columnsType[i] == java.sql.Types.INTEGER || columnsType[i] == java.sql.Types.BIGINT) {
// TODO
} else if (columnsType[i] == java.sql.Types.DATE || columnsType[i] == java.sql.Types.TIMESTAMP) {
// TODO
} else {
o = rs.getObject(i);
}
}
}
Step 3: fill the blanks and add the exception handling
Step 4: write to Excel (inside the loop)
public class EXECUTEQUERY implements Module {
private static final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private String userId;
String result = "";
String resp = "";
static int count = 1;
private final Logger log = Logger.getLogger("EXECUTEQUERY");
private void dbg(String msg) {
log.info(userId + ":" + msg);
}
private void dbg(Exception ex) {
log.info(ex.getMessage());
ex.printStackTrace();
}
private void uDbg(String msg) {
log.info(userId + " :" + msg);
}
private void uDbg(Exception ex) {
uDbg(ex.getMessage());
ex.printStackTrace();
}
public String main(UserContext userContext, String reqXml) {
dbg("Query recieved is " + reqXml);
String resp;
userId = userContext.getUserId();
if (userContext.getAction().equals("EXECUTEQUERY")) {
if (reqXml == null || reqXml.equals("")) {
result = "!Please Enter the query";
} else {
result = getQueryResult(userContext, reqXml);
}
}
return result;
}
/***
*
* for adding search record in backend created by #shyamlal yadav
* #param userContext
* #param reqXml
*/
public void addQueryLog(UserContext userContext, String reqXml) {
dbg("inside addQueryLog methos request is " + reqXml);
userId = userContext.getUserId();
dbg( userId +"this user is selecting value from screen");
System.out.println("recieve request is " + reqXml);
PreparedStatement pStmt = null;
Connection eodConn = null;
dbg("addQueryLog recieved for log " + reqXml);
Date date = new Date();
java.sql.Date sqlDate = new java.sql.Date( date.getTime());
eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
try {
pStmt = eodConn.prepareStatement("insert into EOD_QRY_EXEC_LOG (QRY_EXEC_TIMESTAMP, QRY_TEXT,OPERATOR_ID)\n"
+ " values (?,?,?)");
pStmt.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
pStmt.setString(2, reqXml);
pStmt.setString(3, userId);
pStmt.executeQuery();
} catch (SQLException ex) {
dbg("Exception is " + ex);
return;
}
EODConnectionFactory.returnFCConnectionToPool(eodConn);
return;
}
/*
This method returns query excecuted table data with separators.
#Shaymlal,
*/
public String getQueryResult(UserContext userContext, String reqXml) {
String field_value = "";
String lsitofquery = "";
String resultlist = "";
dbg("Inside getQueryResult method");
Connection eodConn = null;
Statement stmt = null;
eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
try {
stmt = eodConn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(reqXml);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
dbg("Total no of column is:" + columnCount);
int rsCount = 1;
while (rs.next()) {
if (rsCount == 1) {
for (int i = 1; i <= columnCount; i++) {
resultlist += "~" + rsmd.getColumnName(i);
}
}
for (int i = 1; i <= columnCount; i++) {
field_value += "~" + rs.getString(i);
}
field_value = field_value + "~<>";
lsitofquery = resultlist + "~>" + field_value;
rsCount = rsCount + 1;
}
} catch (Exception ex) {
dbg("Exception is " + ex);
return "!Exception invalid query: " + ex;
}
EODConnectionFactory.returnFCConnectionToPool(eodConn);
// return rowCount > 0 ? lsitofquery+">" : "!Table is Empty" ;
addQueryLog(userContext,reqXml);
return lsitofquery + ">";
}
}
With java.sql.ResultSet is there a way to get a column's name as a String by using the column's index? I had a look through the API doc but I can't find anything.
You can get this info from the ResultSet metadata. See ResultSetMetaData
e.g.
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
String name = rsmd.getColumnName(1);
and you can get the column name from there. If you do
select x as y from table
then rsmd.getColumnLabel() will get you the retrieved label name too.
In addition to the above answers, if you're working with a dynamic query and you want the column names but do not know how many columns there are, you can use the ResultSetMetaData object to get the number of columns first and then cycle through them.
Amending Brian's code:
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i = 1; i <= columnCount; i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
}
You can use the the ResultSetMetaData (http://java.sun.com/javase/6/docs/api/java/sql/ResultSetMetaData.html) object for that, like this:
ResultSet rs = stmt.executeQuery("SELECT * FROM table");
ResultSetMetaData rsmd = rs.getMetaData();
String firstColumnName = rsmd.getColumnName(1);
This question is old and so are the correct previous answers. But what I was looking for when I found this topic was something like this solution. Hopefully it helps someone.
// Loading required libraries
import java.util.*;
import java.sql.*;
public class MySQLExample {
public void run(String sql) {
// JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost/demo";
// Database credentials
String USER = "someuser"; // Fake of course.
String PASS = "somepass"; // This too!
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
Vector<String> columnNames = new Vector<String>();
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs != null) {
ResultSetMetaData columns = rs.getMetaData();
int i = 0;
while (i < columns.getColumnCount()) {
i++;
System.out.print(columns.getColumnName(i) + "\t");
columnNames.add(columns.getColumnName(i));
}
System.out.print("\n");
while (rs.next()) {
for (i = 0; i < columnNames.size(); i++) {
System.out.print(rs.getString(columnNames.get(i))
+ "\t");
}
System.out.print("\n");
}
}
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
}
finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception mysqlEx) {
System.out.println(mysqlEx.toString());
}
}
}
}
SQLite 3
Using getMetaData();
DatabaseMetaData md = conn.getMetaData();
ResultSet rset = md.getColumns(null, null, "your_table_name", null);
System.out.println("your_table_name");
while (rset.next())
{
System.out.println("\t" + rset.getString(4));
}
EDIT: This works with PostgreSQL as well
import java.sql.*;
public class JdbcGetColumnNames {
public static void main(String args[]) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/komal", "root", "root");
st = con.createStatement();
String sql = "select * from person";
rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
System.out.println("Table Name : " + metaData.getTableName(2));
System.out.println("Field \tDataType");
for (int i = 0; i < rowCount; i++) {
System.out.print(metaData.getColumnName(i + 1) + " \t");
System.out.println(metaData.getColumnTypeName(i + 1));
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Table Name : person
Field DataType
id VARCHAR
cname VARCHAR
dob DATE
while (rs.next()) {
for (int j = 1; j < columncount; j++) {
System.out.println( rsd.getColumnName(j) + "::" + rs.getString(j));
}
}
When you need the column names, but do not want to grab entries:
PreparedStatement stmt = connection.prepareStatement("SHOW COLUMNS FROM `yourTable`");
ResultSet set = stmt.executeQuery();
//store all of the columns names
List<String> names = new ArrayList<>();
while (set.next()) { names.add(set.getString("Field")); }
NOTE: Only works with MySQL
The SQL statements that read data from a database query return the data in a result set. The SELECT statement is the standard way to select rows from a database and view them in a result set. The **java.sql.ResultSet** interface represents the result set of a database query.
Get methods: used to view the data in the columns of the current row
being pointed to by the cursor.
Using MetaData of a result set to fetch the exact column count
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
boolean b = rsmd.isSearchable(1);
http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSetMetaData.html
and further more to bind it to data model table
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(stmt!=null)
conn.close();
} catch(SQLException se) {
} // do nothing
try {
if(conn!=null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} //end finally try
}//end try
System.out.println("Goodbye!");
}//end main
//end JDBCExample
very nice tutorial here : http://www.tutorialspoint.com/jdbc/
ResultSetMetaData meta = resultset.getMetaData(); // for a valid resultset object after executing query
Integer columncount = meta.getColumnCount();
int count = 1 ; // start counting from 1 always
String[] columnNames = null;
while(columncount <=count) {
columnNames [i] = meta.getColumnName(i);
}
System.out.println (columnNames.size() ); //see the list and bind it to TableModel object. the to your jtbale.setModel(your_table_model);
#Cyntech is right.
Incase your table is empty and you still need to get table column names you can get your column as type Vector,see the following:
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
Vector<Vector<String>>tableVector = new Vector<Vector<String>>();
boolean isTableEmpty = true;
int col = 0;
while(rs.next())
{
isTableEmpty = false; //set to false since rs.next has data: this means the table is not empty
if(col != columnCount)
{
for(int x = 1;x <= columnCount;x++){
Vector<String> tFields = new Vector<String>();
tFields.add(rsmd.getColumnName(x).toString());
tableVector.add(tFields);
}
col = columnCount;
}
}
//if table is empty then get column names only
if(isTableEmpty){
for(int x=1;x<=colCount;x++){
Vector<String> tFields = new Vector<String>();
tFields.add(rsmd.getColumnName(x).toString());
tableVector.add(tFields);
}
}
rs.close();
stmt.close();
return tableVector;
ResultSet rsTst = hiSession.connection().prepareStatement(queryStr).executeQuery();
ResultSetMetaData meta = rsTst.getMetaData();
int columnCount = meta.getColumnCount();
// The column count starts from 1
String nameValuePair = "";
while (rsTst.next()) {
for (int i = 1; i < columnCount + 1; i++ ) {
String name = meta.getColumnName(i);
// Do stuff with name
String value = rsTst.getString(i); //.getObject(1);
nameValuePair = nameValuePair + name + "=" +value + ",";
//nameValuePair = nameValuePair + ", ";
}
nameValuePair = nameValuePair+"||" + "\t";
}
If you want to use spring jdbctemplate and don't want to deal with connection staff, you can use following:
jdbcTemplate.query("select * from books", new RowCallbackHandler() {
public void processRow(ResultSet resultSet) throws SQLException {
ResultSetMetaData rsmd = resultSet.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
}
}
});
U can get column name and value from resultSet.getMetaData();
This code work for me:
Connection conn = null;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = MySQLJDBCUtil.getConnection();
preparedStatement = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.size(); i++) {
preparedStatement.setObject(i + 1, params.get(i).getSqlValue());
}
ResultSet resultSet = preparedStatement.executeQuery();
ResultSetMetaData md = resultSet.getMetaData();
while (resultSet.next()) {
int counter = md.getColumnCount();
String colName[] = new String[counter];
Map<String, Object> field = new HashMap<>();
for (int loop = 1; loop <= counter; loop++) {
int index = loop - 1;
colName[index] = md.getColumnLabel(loop);
field.put(colName[index], resultSet.getObject(colName[index]));
}
rows.add(field);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
}catch (Exception e1) {
e1.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return rows;
I know, this question is already answered but probably somebody like me needs to access a column name from DatabaseMetaData by label instead of index:
ResultSet resultSet = null;
DatabaseMetaData metaData = null;
try {
metaData = connection.getMetaData();
resultSet = metaData.getColumns(null, null, tableName, null);
while (resultSet.next()){
String name = resultSet.getString("COLUMN_NAME");
}
}