I am running an SQL query on a AS400 table.
I dont know in advance the columns names i am extracting in my SQL.
in my ResultSet i need to:
get the result set columns (MetaData of the result records - one time).
for each record on the set get the values of the columns.
How can i do this?
There are DataBaseMetaData retrieved from Connection.getMetaData() and ResultSetMetaData from a ResultSet.
Some example java code snipped that may help you:
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM MY_TABLE" );
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
/*if you need the column names...*/
//for( int i = 1; i <= numberOfColumns ) {
// rsmd.getColumnName( i );
//}
List<Object[]> result = new ArrayList<Object[]>();
while( rs.next() ) {
Object[] values = new Object[ numberOfColumns ];
for( int index = 0; index < numberOfColumns; ) {
values[ index ] = rs.getObject( ++index );
}
result.add( values );
}
Related
I have been developing small program in java, i made jtable and connect it to mysql, but it only shows 4 rows only no matter how big my data is...here is jtable in java
and here is mysql table data..
con = DBconnect.connect();
String[] columnNames = {"Name", "UserName", "UserType"};
model.setColumnIdentifiers(columnNames);
jTable1.setModel(model);
jTable1.setShowGrid(false);
try {
PreparedStatement pst;
pst = con.prepareStatement("select * from courses");
ResultSet rs = pst.executeQuery();
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
int i = 0;
for(i = 0; i <= columns; i++){
if (rs.next()) {
uname = rs.getString("C_ID");
email = rs.getString("C_NAME");
pass = rs.getString("C_TYPE");
model.addRow(new Object[]{uname, email, pass});
}
}
You are mixing columns and rows, for(i = 0; i <= columns; i++) will only read 4 records/rows (because you have 3 columns) .
Simply browse the resultset with while(rs.next()) to get all the data :
while(rs.next()){
uname = rs.getString("C_ID");
email = rs.getString("C_NAME");
pass = rs.getString("C_TYPE");
model.addRow(new Object[]{uname, email, pass});
}
i have created jtable but it doesn't show the last column name i don't know what i did wrong in code database have 4 columns id , name, fathername and phone number but jtable only show 3 columns.
public void load() {
try {
DBO db = new DBO();
con = db.connect();
String sql = "Select * from personinfo";
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
DefaultTableModel tb = new DefaultTableModel();
Vector col = new Vector();
for (int i = 1; i < count; i++) {
col.addElement(rsmd.getColumnName(i));
}
tb.setColumnIdentifiers(col);
while (rs.next()) {
Vector rows = new Vector();
for (int j = 1; j < rsmd.getColumnCount(); j++) {
rows.addElement(rs.getString(j));
}
tb.addRow(rows);
PersonTable.setModel(tb);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
I think you should use
pst.setString(1, "%"+name.getText()+"%");
when creating a prepared statement ? is used to replace bind variables. Values which you are not using as bind variables cannot be used the way you want, in this case using like. You can most probably go through this PreparedStatement IN clause alternatives?
Your question is quiet easily a duplicate Using “like” wildcard in prepared statement
I have a jTable with 4 columns and 6 rows. i want to iterate thru the rows picking up the values of column index0 which is my ID column and passing it to a count sql query. i have written the below code which is not working because i haven't figured out how to pass the columns values after iterating through the table.
can someone please let me know what am doing wrong on my code please.
for (int row = 0; row > jTable2.getRowCount(); row++){
for (int col =0; col > jTable2.getColumnCount(); col ++)
try{
DefaultTableModel model = (DefaultTableModel)jTable2.getModel();
String selected = model.getValueAt(row, col+1).toString();
String sql = "select COUNT(COURSEBOOKED) from APP.BOOKCOURSE where COURSEBOOKED = '"+selected+"'";
try(Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
PreparedStatement pst = con.prepareStatement(sql);) {
ResultSet rs = pst.executeQuery();
while(rs.next()){
String Sum = rs.getString("COUNT(COURSEBOOKED)");
System.out.println(Sum);
if (rs.wasNull()){
System.out.println("No record found");
}
}
}
catch(SQLException e){
}
}
catch(Exception e){
}
}
This is the final code that came up with after the changes.
String sql = "select COUNT(COURSEBOOKED) as count from APP.BOOKCOURSE where COURSEBOOKED =?";
try(Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
PreparedStatement pst = con.prepareStatement(sql);){
for(int row = 0; row < jTable2.getRowCount(); row++){
DefaultTableModel model = (DefaultTableModel)jTable2.getModel();
String selected = model.getValueAt(row, 1).toString();
pst.setString(1, selected);
try(ResultSet rs = pst.executeQuery();){
while (rs.next()){
String Sum = rs.getString("count");
System.out.println(Sum);
}
}
}
}
catch(SQLException e){
JOptionPane.showMessageDialog(this, e);
}
Which brings me to my next question. AM not sure whether i should start a new thread for it or continue on this one. My challenge is that i now want to append an addition column to the existing 4 columns on the current jTable2 and display the values of the above query. to add a new column i have used this code,
TableColumn c = new TableColumn();
c.setHeaderValue("Training accomplished");
model.addColumn(c);
This adds the column but populates its with values from column index0. how do i get the new added column to be populated by the values held in Sum from the query above.
You should use something like below. Note that I haven't tested this code so far, so you might need to debug it. Also check the comments on your question.
String sql = "select COUNT(COURSEBOOKED) as count from APP.BOOKCOURSE where COURSEBOOKED = ?";
try(
Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
PreparedStatement pst = con.prepareStatement(sql);){
for (int row = 0; row < jTable2.getRowCount(); row++){
DefaultTableModel model = (DefaultTableModel)jTable2.getModel();
String selected = model.getValueAt(row, 0).toString();
pst.setString(1, selected);
ResultSet rs = pst.executeQuery();
while(rs.next()){
String Sum = rs.getString("count");
System.out.println(Sum);
if (rs.wasNull()){
System.out.println("No record found");
}
}
}
}
catch(SQLException e){
}
catch(Exception e){
}
ResultSet rs = statement.executeQuery("SELECT COUNT(DISTINCT `id`) FROM `users`");
in MySQL i have answer "5" , how to get this 5 from resultset in java? int.
Get it as an int column :
int count = -1;
if (rs.next()) {
count = rs.getInt(1);
}
Try aliasing the COUNT(DISTINCT ID), then retrieving the alias from the ResultSet. This will be more readable and easier to maintain if you end up adding more logic to the query later.
ResultSet rs = statement.executeQuery("SELECT COUNT(DISTINCT `id`) as NUM_ROWS FROM `users`");
int count = -1;
if(rs.next())
{
count = rs.getInt("NUM_ROWS");
}
what I want to do :
input sql statement, and get the column name set . like this :
select email as "邮件" from t_user
2.what I hava done:
String url = "jdbc:mysql://127.0.0.1:3306/testcode?useUnicode=true&characterEncoding=utf8";
Statement st = conn.createStatement();
st.setFetchSize(1);
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData rmd = rs.getMetaData();
int columnCount = rmd.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String column = rmd.getColumnName(i);
}
what's problem I got:
the column name is garbage characters(except english letters),but the resultset is ok.