I am connecting to a sqlite database and grabbing all the columnnames. What i need help with is by putting those columnnames in rs.getString and inserting the values which are grabbed in a String Array which then can be set on the tablemodel.
My code now:
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i = 1; i < columnCount + 1; i++ ) {
String name = rsmd.getColumnName(i);
System.out.println(name);
// Do stuff with name
model.setColumnCount(i);
}
while ( rs.next() ) {
String value1 = "";
String value2 = "";
String value3 = "";
String value4 = "";
value1 = rs.getString("SNO");
value2 = rs.getString("SNAME");
value3 = rs.getString("STATUS");
value4 = rs.getString("CITY");
model.addRow(new Object[] { value1,value2,value3,value4});
}
What i would want it to be:
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i = 1; i < columnCount + 1; i++ ) {
String name = rsmd.getColumnName(i);
System.out.println(name);
// Do stuff with name
model.setColumnCount(i);
}
while ( rs.next() ) {
String values[];
values[] = rs.getString(name);
model.addRow(new Object[] {values[]});
}
Don't keep calling model.setColumnCount(i);. Just set it once (outside the for loop), like this model.setColumnCount(columnCount); Also
// Do stuff with name
model.setColumnCount(i); // Not this...
// Do stuff with name
model.setColumnName(i, name); // Something like this... that is set the name
Related
This question already has answers here:
Retrieve column names from java.sql.ResultSet
(14 answers)
Closed 5 years ago.
try{
connection = dataSource.getConnection();
callableStatement.setInt(2, clientId);
....... // some stuff
resultSet = callableStatement.executeQuery();
}
Now I have a resultSet , but don't know column names? How do I retrive that?
try this...
ResultSetMetaData rsmd = resultSet.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
}
resultSet.getMetadata() returns you a ResultSetMetaData object that has the column names (e.g. resultSet.getMetadata().getColumnName(1) )
show this:
ResultSetMetaData rsmd = resultSet.getMetaData();
String name = rsmd.getColumnName(1);
you can use ResultSetMetaData
ResultSetMetaData metadata = resultSet.getMetaData();
int columnCount = metadata.getColumnCount();
ArrayList<String> columns = new ArrayList<String>();
for (int i = 1; i < columnCount; i++) {
String columnName = metadata.getColumnName(i);
columns.add(columnName);
}
Following code helps to get the column names of the table.
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnsCount = rsmd.getColumnCount();
int i=1;
while (i <= columnsCount){
String columnName = rsmd.getColumnName(i);
i++;
}
I'am trying to update table from multiple columns names(lo1,lo2,...) that are to be taken dynamically. But the values are not getting updated in database.
column names are co1,co2....
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
PreparedStatement pstmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/netbeans","root","");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM colo");
rs = st.executeQuery("SELECT COUNT(*) FROM colo");
// get the number of rows from the result set
rs.next();
int rowCount = rs.getInt(1);
//txt_ans.setText(String.valueOf(rowCount));
int num_1 =300;
int num_2 =200;
int num_3 =300;
int num_4 =400;
String value = null;
int value1 ;
for(int i=1;i<=rowCount;i++)
{
String sql =("SELECT * FROM colo WHERE id = '"+i+"'");
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery(sql);
while(rs.next())
value = rs.getString("co1");
//txt_ans.setText(String.valueOf(value));
String x = "co2";
if(value.equals("lo1"))
{
// value1= 1;
// txt_ans.setText(String.valueOf(value1));
String sql1 =("update colo set '"+x+"' = '"+num_1+"' where id = '"+i+"'");
pstmt = conn.prepareStatement(sql1);
int r = pstmt.executeUpdate(sql1);
txt_ans.setText(String.valueOf(r));
}
else if(value.equals("lo2"))
{
// value1= 1;
// txt_ans.setText(String.valueOf(value1));
String sql1 =("update colo set '"+ x +"' = '"+num_2+"' where id = '"+i+"'");
pstmt = conn.prepareStatement(sql1);
int r = pstmt.executeUpdate(sql1);
txt_ans.setText(String.valueOf(r));
}
else
{
value1 = 9009;
txt_ans.setText(String.valueOf(value1));
}
}
The problem is with using single quotes for column name i.e, like 'x', so just remove them as shown below:
String sql1 =("update colo set " + x + " = ? where id = ?");//no single quote for x
pstmt = conn.prepareStatement(sql1);
pstmt.setString(1, num_1);
pstmt.setString(2, i);
int r = pstmt.executeUpdate(sql1);
Also, always use prepareStatement's setString, etc.. methods for setting the values which is recommended.
Apply the same concept for the other query inside the else if(value.equals("lo2")) block as well.
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
This question already has answers here:
Retrieve column names from java.sql.ResultSet
(14 answers)
Closed 8 years ago.
Hello I'm trying to make an error when there is no matched student...
and it will display like this
No matching records found and I want the column name still the same but still not figuring it out... can some one tell me if this is right??
Heres my function for that... and I add comment there where I put the error... but i don't know how to get the columnname
public void SearchTableStudent() {
String tempSearchValue = searchStudent.getText().trim();
boolean empty = true;
sql = "SELECT student_id as 'Student ID',"
+ "concat(lastname, ' , ', firstname, ' ', middlename) as 'Name'"
+ "FROM user "
+ "WHERE CAST(student_id as CHAR) LIKE '%" + tempSearchValue + "%'";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
table.setModel(DbUtils.resultSetToTableModel(rs));
empty = false;
}
if(empty) {
String error = "";
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"No matching records found",null}
},
new String [] {
/** I WANT TO PUT THE SAME COLUMN NAME ON MY DATABASE SELECTED BUT DON't Know
WHAT FUNCTION TO DO*/
}
));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
I try like this but still gave me NULL!!!
this code is below of empty = false;
for(int i=0; i<table.getColumnCount(); i++) {
test[i] = table.getColumnName(i);
}
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount(); //number of column
String columnName[] = new String[count];
for (int i = 1; i <= count; i++)
{
columnName[i-1] = metaData.getColumnLabel(i);
System.out.println(columnName[i-1]);
}
Try this.
ResultSetMetaData meta = resultset.getMetaData();
Integer columncount = meta.getColumnCount();
int count = 1 ; // start counting from 1 always
String[] columnNames = new String[columncount];
while(count<=columncount){
columnNames [count-1] = meta.getColumnLabel(count);
count++;
}
Since here your expecting is to get the columns alias instead of column name, so you have to use ResultSetMetaData.getColumnLabel instead of ResultSetmetaData.getColumnName.
Get ResultSetMetaData using ResultSet#getMetaData():
ResultSetMetaData meta = rs.getMetaData();
And then to get column name of 1st column:
String col1Name = meta.getColumnLabel(1);
Similarly to get column name of 2nd column:
String col2Name = meta.getColumnLabel(2);
Get the metadata
ResultSetMetaData metaData = rs.getMetaData();
Then you can do:
String columnName = metaData.getColumnName(int index);
ResultSetMetaData doc
rs.getMetaData().getColumnName(int i);
and do not concat the query param!
In the below code I am copying resultset content to arraylist. First part of the wile loop i.e while(RS.next()) is returing the results but when cursor moves to
Next while loop i.e while(SR.next()) I am getting "result set is closed". Please help me where I am doing mistake.
String SSQ = "select DISTINCT S_NUMBER from OTG.S_R_VAL" +
" WHERE R_TS = (SELECT MAX(R_TS) FROM OTG.S_R_VAL) order by S_NUMBER";
String SDS = "SELECT DISTINCT S_NUMBER FROM OTG.S_R_VAL AS STG WHERE S_NUMBER NOT IN" +
"(SELECT S_NO FROM OTG.R_VAL AS REV WHERE STG.S_NUMBER = REV.S_NO )";
String SSR = "SELECT DISTINCT S_NO FROM OTG.R_VAL where S_NO != 'NULL' order by S_NO";
String SSO = "Select O_UID from OTG.OPTY where C_S_NO IN" +
"( SELECT DISTINCT S_NUMBER FROM OTG.S_R_VAL AS STG WHERE S_NUMBER NOT IN(SELECT S_NO FROM OTG.R_VAL AS REV WHERE STG.S_NUMBER = REV.S_NO ))";
//Statement statement;
try {
connection = DatabaseConnection.getCon();
statement = connection.createStatement();
statement1 = connection.createStatement();
statement2 = connection.createStatement();
statement3 = connection.createStatement();
statement4 = connection.createStatement();
ResultSet RS = statement1.executeQuery(selectQuery);
ResultSet DS = statement2.executeQuery(Distinct_SiebelNo);
ResultSet SR = statement3.executeQuery(SiebelNo_Rev);
ResultSet SO = statement4.executeQuery(selected_OppId);
ArrayList<String> RSList = new ArrayList<String>();
ArrayList<String> SRList = new ArrayList<String>();
/* ResultSetMetaData resultSetMetaData = RS.getMetaData();
int count = resultSetMetaData.getColumnCount();*/
int count=1;
System.out.println("******count********"+count);
while(RS.next()) {
int i = 1;
count=1;
while(i < count)
{
RSList.add(RS.getString(i++));
}
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
/* ResultSetMetaData resultSetMetaData1 = SR.getMetaData();
int count1 = resultSetMetaData1.getColumnCount();*/
int count1=1;
while(SR.next()) {
int i = 1;
while(i < count1)
{
SRList.add(SR.getString(i++));
}
System.out.println(SR.getString("SIEBEL_NO"));
SRList.add( SR.getString("SIEBEL_NO"));
}SR.close();
connection.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The logic of each loop is flawed.
int count=1;//Count is being set to one
while(RS.next()) {
int i = 1;//i is being set to one
count=1;//count again set to one
while(i < count) //condition will always fail as one is never less than one
{
RSList.add(RS.getString(i++));//Code is never Reached
}
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
The second while is not needed. Just use this:
int count = 1;
while(RS.next()) {
RSList.add(RS.getString(count++));
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
EDIT
int count1=1;
while(SR.next()) {
SRList.add(SR.getString(count1++));
System.out.println(SR.getString("SIEBEL_NO"));
SRList.add( SR.getString("SIEBEL_NO"));
}
EDIT 2:
for (String s : RSList)
for(String s1 : SRList)
if (s.equals(s1))
//Do what you need
You are using the first resultset (RS) in the second loop (System.out.println line)