I have column family that have two primary keys
"CREATE TABLE compositkeys(user_name varchar," +
"user_id int,"+
"name varchar," +
"gender varchar," +
"PRIMARY KEY (user_name,user_id)" +
")";
I have created this in Java now i inserted 6 rows with on one user_name(sunil) primarykey with different id now when I try to retrieve all the value in sunil primary key it gives me only one detail
String qry = "select * from compositkeys where user_name = 'sunil' order by user_id";
Statement smt = con.createStatement();
//smt.executeUpdate(qry);
ResultSet rs = smt.executeQuery(qry);
//rs.get
int r = rs.getRow();
System.out.println(r);
ResultSetMetaData rm = rs.getMetaData();
int columnCount = rm.getColumnCount();
System.out.println(columnCount);
for(int i=1;i<=columnCount;i++)
{
String name = rm.getColumnName(i);
System.out.print(rm.getColumnName(i));
System.out.println(" = "+rs.getString(name));
System.out.println("--------------------------------------------------");
}
It gives me only one output. Is there any thing wrong in query? I want all the data under the key sunil.
You have a single loop that loops over the columns in a returned row, but you only ask for one row (that's the rs.getRow() method). You should put the rs.getRow() call and the following logic to write the results into an outer loop that iterates as long as getRow() doesn't return null. This out loop is what will retrieve all of a user's ids.
Related
I have data in following format:
HashMap<PageID, Set<SubscriberIDS>>
What I need to check is how many SubscriberIDS for each of the PageIDs do not exist in a MySQL table already. MySQL table has PageID and SubscriberID columns.
This is what I have so far:
String NEW_SUBSCRIBER_COUNT = "SELECT ? - COUNT(*) as new_subscribers from FB_SUBSCRIPTIONS WHERE PAGEID=? AND SUBSCRIBERID IN (?)";
First parameter being numberOFSubscriberIDs, Second being PageId and Third being SubscriberIds
but this will need to be hit for each pageId. How do I modify it to give me number of new subscribers for each PageID using single query.
Is there any specific need to do it in one query? Because while it can, it might actually be more readable to use your original solution and invoke a query for each page id. In any case, what you want can't be done in a single line, so you need to expect to loop at a given point.
// Build dynamic query
StringBuilder whereClause = new StringBuilder();
Iterator<PageID> it = yourMap.keySet().iterator();
while(it.hasNext()){
PageID key = it.next();
Set<SubscriberIDS> value = yourMap.get(key);
// You need to fill the 'IN' clause with multiple parameters, one for each subscriber id
StringBuilder inClause = new StringBuilder();
for(SubscriberIDS subId : value){
if(inClause.length > 0){
inClause.append(", ");
}
inClause.append("?");
preparedStatement.setInt(paramIndex++, subId.getId());
}
// For each page id we append a new 'OR' to our query
if(whereClause.lenght > 0){
whereClause.append(" OR ");
}
whereClause.append("(PAGEID=? AND SUBSCRIBERID IN (").append(inClause.toString()).append("))");
}
String query = "SELECT PAGEID, COUNT(SUBSCRIBERID) AS SUBSCRIBERS FROM FB_SUBSCRIPTIONS WHERE " + whereClause.toString() + " GROUP BY PAGEID";
// Create prepared statement and set parameters
PreparedStatement preparedStatement = connection.prepareStatement(query);
int paramIndex = 0;
it = yourMap.keySet().iterator();
while(it.hasNext()){
PageID key = it.next();
Set<SubscriberIDS> value = yourMap.get(key);
preparedStatement.setInt(paramIndex++, key.getId());
for(SubscriberIDS subId : value){
preparedStatement.setInt(paramIndex++, subId.getId());
}
}
// Execute query, loop over result and calculate new subscriptions
ResultSet rs = preparedStatement.executeQuery();
while(rs.next()){
int pageId = rs.getInt("PAGEID");
int newSubscriptions = yourMap.get(pageId).size() - rs.getInt("SUBSCRIBERS");
System.out.println(pageId + ", " + newSubscriptions);
}
Given following data in your map:
PAGEID SUBSCRIBERIDS
1 1,3,4,5,9
2 3,4,5,6,8,9
3 2,5,6
And following data in the DB:
PAGEID SUBSCRIBERIDS
1 3,4,10,11
2 1,2,5,7
3 1,2,5,6,7,8,9
This should give following output:
1,3
2,6
3,0
I haven't actually ran the code, so it might need some adjustments, but it gives you the general idea...
I am working on a option in a Menu function that posts the car for the sale in a database. The option asks for the user to enter the year, make, condition and price, which is then inserted into the table car_sale in the database. However, a unique listing_no must also be generated during this option. I cannot define my tables to uniquely generate the 10 digit number the option but I must code the program to insert uniquely generated listing_no. Below you will find the code of me trying to do this, however the code only works in Oracle but I cannot use Oracle. I can only PostGreSQL and Java. Therefore, my problem arises as the functions and relations I am using cannot be used in PostGre.
Code to Generate Listing No:
public int generateListingNo() throws SQLException
{
int listingSeq = 0;
Statement select = connection.createStatement();
result = select.executeQuery("select (to_char(sysdate,'yyyymmdd')||AUDIT_SEQ.NEXTVAL)valnext from dual");;
if(result.next())
{
listingSeq = result.getInt(1);
}
int seq = listingSeq;
return seq;
}
Code in The Option Function to insert the lisitng_no generated from generateListingNo()
public void option() throws SQLException
{
int listing_no = generateListingNo();
// insert information into books_for_sale table
sql_insert = "INSERT INTO car_sale VALUES(" + listing_no +", "
+ "'" + year + "'" + ", " +
"'" + make + "'" +", " +
"'" + condition + "'" + ", "
+ price + ")";
Erros I am Getting:
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: relation "dual" does not exist
Position: 69 at
org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:217)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:421)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:318)
at org.postgresql.jdbc.PgStatement.executeQuery(PgStatement.java:281)
Creating the car_sale table
create table car_sale(
listing_no int not null,
year varchar not null,
make varchar not null,
condition varchar not null,
price decimal(12,2) not null,
primary key (listing_no),
Change you query for generateListingNo as below:
select q from (select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ') )q )sq
or
select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ')) as newseqval
or on your cocde:
public int generateListingNo() throws SQLException
{
int listingSeq = 0;
Statement select = connection.createStatement();
result = select.executeQuery("select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ')) as newseqval");;
if(result.next())
{
listingSeq = result.getInt(1);
}
int seq = listingSeq;
return seq;
}
Since you dont have sequence :
Either create sequence using below query:
CREATE SEQUENCE public."AUDIT_SEQ"
INCREMENT 1
START 1
MINVALUE 1
MAXVALUE 9223372036854775807
CACHE 1;
or use UUID:
public String generateListingNo() throws SQLException
{
return UUID.randomUUID().toString();
}
your table structure will need to change :
create table car_sale(
listing_no varchar not null,
year varchar not null,
make varchar not null,
condition varchar not null,
price decimal(12,2) not null,
primary key (listing_no),
For PostgreSQL, you have to call query this way from java :
SELECT nextval('ACCOUNT_TRANSACTION_NO')
I've created a very simple table, and am attempting to insert into it. The table exists, but nothing I try to insert sticks; the resultSet is always null. I think I'm auto-incrementing my primary key correctly. Any ideas? Thank you!
String createGenreTableSQL = "CREATE TABLE Genre (GenreID INTEGER NOT NULL GENERATED ALWAYS " +
"AS IDENTITY (START WITH 1, INCREMENT BY 1), genreName varchar(60))";
statement.executeUpdate(createGenreTableSQL);
String prepGenreInsert = "INSERT INTO Genre(genreName) VALUES (?)";
psInsert = conn.prepareStatement(prepGenreInsert);
allStatements.add(psInsert);
psInsert.setString(1,"Television");
psInsert.setString(1,"Movies");
psInsert.setString(1,"VideoGames");
psInsert.setString(1,"Animes");
String fetchAllDataSQL = "SELECT * from Genre";
resultSet = statement.executeQuery(fetchAllDataSQL);
while (resultSet.next()) { //resultSet shows null
int genreID = resultSet.getInt("genreID");
String genreName = resultSet.getString("genreName");
System.out.println("GenreID:" + genreID + " Name: " + genreName);
}
The setString method simply binds the given value to the given parameter index. It does not actually execute the query. I believe what you want to do is
psInsert.setString(1,"Television");
psInsert.execute();
psInsert.setString(1,"Movies");
psInsert.execute();
psInsert.setString(1,"VideoGames");
psInsert.execute();
psInsert.setString(1,"Animes");
psInsert.execute();
Using Java/Selenium/Excel sheets I have an automation script. When verifying information in the database, I am doing something like this:
//Get values from Excel. Excel user will specify what table and what user
String table=currentTestSuiteXLS.getCellData(currentTestCaseName, "table",currentTestDataSetID);
String user=currentTestSuiteXLS.getCellData(currentTestCaseName, "user",currentTestDataSetID);
//Run query
PreparedStatement pstmt1 = conn.prepareStatement("SELECT * FROM " + table +" WHERE User = '" + user + "' ORDER BY 1 DESC LIMIT 1;");
if(table.equals("A")){
rs1.next();
//Get results from A table
String db_TableAColumn1=rs1.getString("TableAColumn1");
String db_TableAColumn2=rs1.getString("TableAColumn2");
String db_TableAColumn3=rs1.getString("TableAColumn3");
//Get values from excel
String excel_TableAColumn1=currentTestSuiteXLS.getCellData(currentTestCaseName, "TableAColumn1",currentTestDataSetID);
String excel_TableAColumn2=currentTestSuiteXLS.getCellData(currentTestCaseName, "TableAColumn2",currentTestDataSetID);
String excel_TableAColumn3=currentTestSuiteXLS.getCellData(currentTestCaseName, "TableAColumn3",currentTestDataSetID);
if(db_TableAColumn1.equals(excel_TableAColumnA)) { ...
if(db_TableAColumn2.equals(excel_TableAColumn2)) { ...
if(db_TableAColumn3.equals(excel_TableAColumn3)) { ...
if(table.equals("B")){
rs1.next();
//Get results from B table
String db_TableBColumn1=rs1.getString("TableBColumn1");
String db_TableBColumn2=rs1.getString("TableBColumn2");
String db_TableBColumn3=rs1.getString("TableBColumn3");
//Get values from excel
String excel_TableBColumn1=currentTestSuiteXLS.getCellData(currentTestCaseName, "TableBColumn1",currentTestDataSetID);
String excel_TableBColumn2=currentTestSuiteXLS.getCellData(currentTestCaseName, "TableBColumn2",currentTestDataSetID);
String excel_TableBColumn3=currentTestSuiteXLS.getCellData(currentTestCaseName, "TableBColumn3",currentTestDataSetID);
if(db_TableBColumn1.equals(excel_TableBColumn1)) { ...
if(db_TableBColumn2.equals(excel_TableBColumn2)) { ...
if(db_TableBColumn3.equals(excel_TableBColumn3)) { ...
So this is currently working fine. However, it is not very scalable.
If we want to start to check a new column on the A table (or if a new column is added) we need to update the java code. We only want to modify the excel sheet. Is there a way to parse all the columns from the result set, and if a column is in the excel sheet then we check to see if it exists in the result set, if so, then check to see if the expected values match up?
Is there a way to do For each column in the table
String GiveAName= rs1.getString(1); until all columns are given a name
Then if each column in specified in excel has a value, match up.
Instead of defining everything like:
String db_TableAColumn1=rs1.getString("TableAColumn1");
or
String db_TableAColumn1= rs1.getString(1);
Thanks.
Use ResultSetMetaData http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSetMetaData.html,
It will allow you to dynamically retrieve column names of a table.
example:
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
while (rs.next()){
for(int i=1; i<=columns; ++i){
System.out.println("Column name: " + md.getColumnName(i) + " Col Value: " +rs.getObject(i));
}
}
In my current project, I have a function with argument (e.g., int badgID in the following code snippet). This function connects with Apache Derby database, creates table (e.g., FIRSTTABLE), then query to FIRSTTABLE table. The query statement uses function argument for query (e.g., ID = $badgeID ). My question:
Is ID = $badgeID the right way from a syntax point of view?. I have tried this case, but it is not working.
public void getprofile (int badgeID) {
// Create connection with Apache-Derby Database.
// Create table in Apache Derby datbase.
String createString = " CREATE TABLE FIRSTTABLE "
+ "(ID INT PRIMARY KEY, "
+ "PREF INT, "
+ " NAME VARCHAR(12))";
// SQL query on table
querystmt = "SELECT * FROM FIRSTTABLE WHERE ID = $badgeID"
}
that's php syntax...
in java you would write
String querystmt = "SELECT * FROM FIRSTTABLE WHERE ID = " + badgeID;