Selecting records from two tables - java

I have the following snippet code:
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from books");
ResultSetMetaData resMetaData = rs.getMetaData();
int nCols = resMetaData.getColumnCount();
for (int kCol = 1; kCol <= nCols; kCol++) {
System.out.println(resMetaData.getColumnName(kCol));
}
while (rs.next()) {
for (int kCol = 1; kCol <= nCols; kCol++) {
String s = null;
if (kCol == nCols){
Statement stmt1 = conn.createStatement();
ResultSet rs1 = stmt1.executeQuery("select category_name from categories where category_id = " + rs.getString(kCol));
s = rs1.getString(2);
}
else{
s = rs.getString(kCol);
}
System.out.println(s);
}
}
In my data base I have two tables: books and categories. In both table I have a column *category_id*. The code selects records from the table books. The *category_id* from this table matches the *category_id* from table categories. In this table I have one more row: category_name. I want that the app to write the name from the *category_name* that matches the category_id in table books. I tried but I failed. So, could you give me any idea ?
Thank you

Related

Comparison of different values from ResultSet to database SQL Query

I'm new to java.I have a SQL Query that gives the following output
logtime 2014-09-02 16:05:10.0
BL1_data_SS_ST 2
BL2_data_SS_ST 2
BL3_data_SS_ST 2
BL4_data_SS_ST 1
BL5_data_SS_ST 0
BL6_data_SS_ST 2
/* continues till BL27_data_SS_ST */
st1_prmt_status_p45 1
beam_current 110.58
beam_energy 2500.0635
I have only one row in my output and 31 columns. I'm using Java and JSP .
EDIT
The above result is retrieved by the following method
public String[][] beamline_Status() {
int i = 0;
try {
con = getConnection();
stmt = con.createStatement();
String sql = "SELECT TOP 1 c.logtime, a.BL1_data_SS_ST,a.BL2_data_SS_ST,a.BL3_data_SS_ST,a.BL4_data_SS_ST,a.BL5_data_SS_ST,a.BL6_data_SS_ST,a.BL7_data_SS_ST,a.BL8_data_SS_ST,a.BL9_data_SS_ST,a.BL10_data_SS_ST,a.BL11_data_SS_ST, a.BL12_data_SS_ST,a.BL13_data_SS_ST,a.BL14_data_SS_ST,a.BL15_data_SS_ST,a.BL16_data_SS_ST,a.BL17_data_SS_ST,a.BL18_data_SS_ST,a.BL19_data_SS_ST,a.BL20_data_SS_ST,a.BL21_data_SS_ST,a.BL22_data_SS_ST,a.BL23_data_SS_ST,a.BL24_data_SS_ST,a.BL25_data_SS_ST,a.BL26_data_SS_ST,a.BL27_data_SS_ST,b.st1_prmt_status_p45,c.beam_current,c.beam_energy from INDUS2_BLFE.dbo.main_BLFE_status a inner join INDUS2_MSIS.dbo.main_MSIS_status b on a.logtime=b.logtime inner join INDUS2_BDS.dbo.DCCT c on b.logtime=c.logtime ORDER BY c.logtime DESC ";
stmt.executeQuery(sql);
rs = stmt.getResultSet();
while (rs.next()) {
for (int j = 0; j < 31; j++) {
a[i][j] = rs.getString(j + 1);
}
}
} catch (Exception e) {
System.out.println("\nException (String code):" + e);
} finally {
closeConnection(stmt, rs, con);
}
return a;
}
Now I wan to define a method which retrieve values from the ResultSet where column values are either 0 or 1. How to do that.
EDIT 2
I'm trying to retrieve the column values from resultset where column value is 1 by following code:-
public String[][] beam_CurrentStatus() {
int i = 0;
try
{
con = getConnection();
stmt = con.createStatement();
String sql = "SELECT TOP 1 c.logtime, a.BL1_data_SS_ST,a.BL2_data_SS_ST,a.BL3_data_SS_ST,a.BL4_data_SS_ST,a.BL5_data_SS_ST,a.BL6_data_SS_ST,a.BL7_data_SS_ST,a.BL8_data_SS_ST,a.BL9_data_SS_ST,a.BL10_data_SS_ST,a.BL11_data_SS_ST, a.BL12_data_SS_ST,a.BL13_data_SS_ST,a.BL14_data_SS_ST,a.BL15_data_SS_ST,a.BL16_data_SS_ST,a.BL17_data_SS_ST,a.BL18_data_SS_ST,a.BL19_data_SS_ST,a.BL20_data_SS_ST,a.BL21_data_SS_ST,a.BL22_data_SS_ST,a.BL23_data_SS_ST,a.BL24_data_SS_ST,a.BL25_data_SS_ST,a.BL26_data_SS_ST,a.BL27_data_SS_ST,b.st1_prmt_status_p45,c.beam_current,c.beam_energy from INDUS2_BLFE.dbo.main_BLFE_status a inner join INDUS2_MSIS.dbo.main_MSIS_status b on a.logtime=b.logtime inner join INDUS2_BDS.dbo.DCCT c on b.logtime=c.logtime ORDER BY c.logtime DESC ";
stmt.executeQuery(sql);
rs = stmt.getResultSet();
while (rs.next()) {
for (int j = 1; j < 31; j++) {
if ((rs.getString(j)) == "1")
a[i][j] = rs.getString(j + 1);
}
}
} catch (Exception e) {
System.out.println("\nException in:" + e);
} finally {
closeConnection(stmt, rs, con);
}
return a;
}
But the result I'm getting of above code is
[[Ljava.lang.String;#ea25c1
If you want entire table in the ResultSet and then obtain only the first and second column out of it you can do like:
Statement stmt=conn.createStatement();
ResultSet rs= stmt.executeQuery("select * from tableName");
rs.getInt(1); //assuming your column is of compatible type
rs.getInt(2);
or the other way is that you retrieve only the first two columns from the DB into your ResultSet

how to get all tables and Their's columns of a specific schema using Java?

I have a database schema that its name is "Navid"
there is many tables in this schema.
definitely each table, has some columns.
what I need is a java class that:
Connect to my database.
Have a method that loop on all tables
2-1. Have an inner loop to define all columns of the table.
Make create table query statement .(I want to create the same table in another database).
Execute that query.
I write some code but I do not know what to do next.
public class automateExport {
static String value;
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// ResultSet rs = null;
String table_name;
String column_name;
String tableName = null;
StringBuilder sb = new StringBuilder(1024);
Connection DB2 = getConnection();
String sql = "SELECT TABSCHEMA,TABNAME,COLNAME FROM SYSCAT.COLUMNS WHERE TABSCHEMA NOT LIKE 'SYS%'";
PreparedStatement mainStmt = DB2.prepareStatement(sql);
ResultSet rs = mainStmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
/* while(rs.next()){
table_name = rs.getString(2);
// for(int i = 1; i <= 1; i ++){
column_name = rs.getString(3);
System.out.println("SSS::::: " + table_name + " " + column_name );
// }
*/
for (int i = 1; i <= rows; i++) {
while (rs.next()) {
table_name = rs.getString(2);
if (i > 1) {
sb.append(", ");
}
column_name = rs.getString(3);
String columnType = rsmd.getColumnTypeName(i);
sb.append(" ").append(column_name).append(" ").append(columnType);
int precision = rsmd.getPrecision(i);
if (precision != 0) {
sb.append("( ").append(precision).append(" )");
}
} // for columns
sb.append(" ) ");
String sql2 = sb.toString();
PreparedStatement m = DB2.prepareStatement(sql);
m.executeQuery();
System.out.println(sb.toString());
}
}
private static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("COM.ibm.db2os390.sqlj.jdbc.DB2SQLJDriver");
Connection connection
= DriverManager.getConnection("jdbc:db2://localhost:50000/navid", "navid", "oracle");
return connection;
}
}

Copying Resultset content to arraylist and comparing both the values

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)

Java ResultSet get Returned Field Names

For standard queries I have not had a problem with this. I simply:
ResultSet rs = stmt.executeQuery("SELECT a, b FROM table_name");
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
for (int i = 1; i < numberOfColumns + 1; i++) {
String fieldName = rsMetaData.getColumnName(i);
System.out.print(fieldName + ", ");
}
But the moment I assign a field name to another name, i.e.
ResultSet rs = stmt.executeQuery("SELECT a AS foo, b AS bar FROM table_name");
It throws an error because fields a and b aren't found.
How should I cater to this? Thanks
There is a difference between column name and column label. The methods in ResultSet expect column labels. So you should use the method ResultSetMetaData.getColumnLabel instead of ResultSetmetaData.getColumnName.

viewing results of mysql query in java

In java, when executing a query like :
statement stm = stm.executeQuery("select * from table1");
How can I view the results of this query on the command prompt ?
Thanks for any help
ResultSet rs = stmt.executeQuery("select * from table1");
int columns = rs.getMetaData().getColumnCount();
StringBuilder message = new StringBuilder();
while (rs.next()) {
for (int i = 1; i <= columns; i++) {
message.append(rs.getString(i) + " ");
}
message.append("\n");
}
System.out.println(message); // print table contents

Categories