I have a problem. When I try to use the "Select distinct" in HSQLDB, the stream of results returns me all rows instead of me returning only distinct rows.
I've tried the following syntax:
SELECT DISTINCT FROM ratings UserID order by UserID;
SELECT DISTINCT (UserID) FROM ratings order by UserID;
SELECT DISTINCT UserID FROM ratings;
SELECT DISTINCT (UserID) FROM ratings;
None of them works. What is the problem?
If anyone able to help me I appreciate.
Thank you.
The function code where I perform the action is as follows:
private void readUserFile(String filename) {
try {
//Verify if file users exists
boolean exists = (new File(filename)).exists();
if (!exists) {
//If file users not exists create one, bases on distinct users that exist in ratings table
ResultSet rsUsers = jdbcTemplate.getDataSource().getConnection().createStatement().executeQuery("SELECT DISTINCT UserID FROM ratings order by UserID;");
List<String> users = new ArrayList<String>();
while (rsUsers.next()) {
users.add(String.valueOf(rsUsers.getInt(1)));
}
rsUsers.close();
//Create and write to file
BufferedWriter f = null;
f = new BufferedWriter(new FileWriter(filename));
for (String user : users) {
f.write(user);
f.newLine();
}
f.close();
}
PreparedStatement prstInsert = con.prepareStatement("INSERT INTO users VALUES (?)");
BufferedReader in = new BufferedReader(new FileReader(filename));
int i = 0;
while (true) {
String s = in.readLine();
if (s == null) { // end of file
log.info("Total imported users: " + i);
break;
}
i++;
int userid = Integer.parseInt(s);
prstInsert.setInt(1, userid);
if (i != 0 && Math.round((double) i / 100) == ((double) i / 100)) {
log.info("Imported users: " + i);
}
prstInsert.executeUpdate();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
Related
public void insertBoard(BoardDTO board) {
Connection conn = null;
Statement stmt = null;
try {
conn = this.getConnection();
conn.setAutoCommit(false);
stmt = conn.createStatement();
String sql = "INSERT INTO board (TITLE, SUB_TITLE, CONTENTS, CREATE_DATE) VALUES"
+ "('"+board.getTitle()+"', '"
+ board.getSubTitle()+"', '"
+ board.getContents()+"', '"
+ board.getFormatCreateDate()+"')";
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet resultSet = stmt.getGeneratedKeys();
resultSet.next();
board.setId(resultSet.getInt(1));
sql = "INSERT INTO attach_file (BOARD_ID, PATH, ORIGINAL_FILE_NAME, SAVE_FILE_NAME) VALUES"
+ "(" + board.getId() +", '"
+ board.getAttachFile().getPath()+"', '"
+ board.getAttachFile().getOriginalFileName()+"', '"
+ board.getAttachFile().getSaveFileName()+"')";
stmt.executeUpdate(sql);
conn.commit();
} catch (SQLException | ClassNotFoundException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
try {
if(stmt != null) stmt.close();
if(conn != null) conn.close();
} catch(SQLException e) {
e.printStackTrace();
}
}
}
I trying to make board on my test website.
I was build that code on my 'FrontController.java' servlet.
after that I run my website and insert some data on that page, but I couldn't find any data on my SQL tables.
is ther any problem on that code?
public class UserDTO {
private String id;
private String email;
private String password;
private int job;
private String gender;
private String introduction;
private Date createDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
.... setter and getters ....
public String getFormatCreateDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateFormat.format(this.createDate);
}
that's my BoardDTO code
You should use Prepared Statement to avoid any sql injection attacks. and also your statement has resource leak problem. fixed all in below method.
public void insertBoard(BoardDTO board) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = this.getConnection();
conn.setAutoCommit(false);
String sql = "INSERT INTO board (TITLE, SUB_TITLE, CONTENTS, CREATE_DATE) VALUES (?,?,?,?)";
pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, board.getTitle());
pstmt.setString(2, board.getSubTitle());
pstmt.setString(3, board.getContents());
pstmt.setString(4, board.getFormatCreateDate());
pstmt.executeUpdate();
ResultSet resultSet = pstmt.getGeneratedKeys();
resultSet.next();
board.setId(resultSet.getInt(1));
resultSet.close();
pstmt.close();
sql = "INSERT INTO attach_file (BOARD_ID, PATH, ORIGINAL_FILE_NAME, SAVE_FILE_NAME) VALUES (?,?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, board.getId());
pstmt.setString(2, board.getAttachFile().getPath());
pstmt.setString(3, board.getAttachFile().getOriginalFileName());
pstmt.setString(4, board.getAttachFile().getSaveFileName());
pstmt.executeUpdate();
conn.commit();
} catch (SQLException | ClassNotFoundException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
try {
if (pstmt != null)
pstmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I have company table where values are inserted
public int SaveCompany(Company objCompany)
{
int CompanyID = 0
try
{
using (var context = new Cubicle_EntityEntities())
{
context.Companies.Add(objCompany); //add entity to the add method
int res = context.SaveChanges(); //insert it into table
if (res > 0)
{
Debug.WriteLine("Data Inserted Successfully");
}
else
{
Debug.WriteLine("Try Again");
}
CompanyID = objCompany.CompanyId;
Debug.WriteLine("CompanyId " + CompanyID);
}
}
catch (Exception ex)
{
CompanyID = 0;
bool rethrow = UserInterfaceExceptionHandler.HandleException(ref ex);
throw ex;
}
return CompanyID;
}
Every time I get res 1,but data not inserted in table.
i'm new to android and java.
i made a cardview and populated it with a simple loop like so:
private ArrayList<DataObject> getTheData(){
ArrayList res = new ArrayList<DataObject>();
for (int index = 0; index < 5; index++){
DataObject obj = new DataObject("shit","happen");
res.add(index,obj);
}
return res;
}
it worked. now i created a database and want to populate it with this data. so i have this:
public ArrayList<DataObject> getData() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList res = null;
try {
res = new ArrayList<DataObject>();
String selectQuery = "SELECT * FROM quotes a LEFT JOIN authors b ON b.author_id=a.quote_author";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Log.d("CHECKDB",cursor.getString(cursor.getColumnIndex("first_name")) + " " + cursor.getString(cursor.getColumnIndex("last_name")));
Log.d("CHECKDB2",cursor.getString(cursor.getColumnIndex("quote_text")));
DataObject obj = new DataObject(
cursor.getString(cursor.getColumnIndex("first_name")) + " " + cursor.getString(cursor.getColumnIndex("last_name")),
cursor.getString(cursor.getColumnIndex("quote_text"))
);
res.add(obj);
} while (cursor.moveToNext());
}
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (db != null)
db.close();
}
return res;
}
the log show all the results, but when i run the app i get the last result the right amount of times. in this case 4 quotes in my database, so i see 4 but the last one 4 times.
please , since i'm new to it, good explanations will be appreciated.
the issue was that my dataobject attributes were set to static
I want to get followers Id's for a particular userId using java program. where I want to implement the cursor concept with rate limit set ... Can any one post me the code.
Use the following code snippet to get follower id. After getting the ids you use show user to get other details. Remember to use this code in background thread like in asynctask.
long[] tempids = null;
ConfigurationBuilder config =
new ConfigurationBuilder()
.setOAuthConsumerKey(custkey)
.setOAuthConsumerSecret(custsecret)
.setOAuthAccessToken(accesstoken)
.setOAuthAccessTokenSecret(accesssecret);
twitter1 = new TwitterFactory(config.build()).getInstance();
while(cursor != 0) {
try {
IDs temp = twitter1.friendsFollowers().getFollowersIDs("username", cursor);
cursor = temp.getNextCursor();
tempids = temp.getIDs();
} catch (twitter4j.TwitterException e) {
System.out.println("twitter: failed");
e.printStackTrace();
return null;
}
if(tempids != null) {
for (long id : tempids) {
ids.add(id);
System.out.println("followerID: " + id);
}
}
}
I am creating a webpage having CellTable.I need to feed this table with data from hbase table.
I have written a method to retrieve data from hbase table and tested it.
But when I call that method as GWT asynchronous RPC method then rpc call succeeds but it returns nothing.In my case it returns empty list.The alert box show list's size as 0.
Following is the related code.
Please help.
greetingService.getDeviceIDData(new AsyncCallback<List<DeviceDriverBean>>(){
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
System.out.println("RPC Call failed");
Window.alert("Data : RPC call failed");
}
public void onSuccess(List<DeviceDriverBean> result) {
//on success do something
Window.alert("Data : RPC call successful");
//deviceDataList.addAll(result);
Window.alert("Result size: " +result.size());
// Add a text column to show the driver name.
TextColumn<DeviceDriverBean> nameColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
Window.alert(object.getName());
return object.getName();
}
};
table.addColumn(nameColumn, "Name");
// Add a text column to show the device id
TextColumn<DeviceDriverBean> deviceidColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
return object.getDeviceId();
}
};
table.addColumn(deviceidColumn, "Device ID");
table.setRowCount(result.size(), true);
// more code here to add columns in celltable
// Push the data into the widget.
table.setRowData(0, result);
SimplePager pager = new SimplePager();
pager.setDisplay(table);
VerticalPanel vp = new VerticalPanel();
vp.add(table);
vp.add(pager);
// Add it to the root panel.
RootPanel.get("datagridContainer").add(vp);
}
});
Code to retrieve data from hbase (server side code)
public List<DeviceDriverBean> getDeviceIDData()
throws IllegalArgumentException {
List<DeviceDriverBean> deviceidList = new ArrayList<DeviceDriverBean>();
// Escape data from the client to avoid cross-site script
// vulnerabilities.
/*
* input = escapeHtml(input); userAgent = escapeHtml(userAgent);
*
* return "Hello, " + input + "!<br><br>I am running " + serverInfo +
* ".<br><br>It looks like you are using:<br>" + userAgent;
*/
try {
Configuration config = HbaseConnectionSingleton.getInstance()
.HbaseConnect();
HTable testTable = new HTable(config, "driver_details");
byte[] family = Bytes.toBytes("details");
Scan scan = new Scan();
int cnt = 0;
ResultScanner rs = testTable.getScanner(scan);
for (Result r = rs.next(); r != null; r = rs.next()) {
DeviceDriverBean deviceDriverBean = new DeviceDriverBean();
byte[] rowid = r.getRow(); // Category, Date, Sentiment
NavigableMap<byte[], byte[]> map = r.getFamilyMap(family);
Iterator<Entry<byte[], byte[]>> itrt = map.entrySet()
.iterator();
deviceDriverBean.setDeviceId(Bytes.toString(rowid));
while (itrt.hasNext()) {
Entry<byte[], byte[]> entry = itrt.next();
//cnt++;
//System.out.println("Count : " + cnt);
byte[] qual = entry.getKey();
byte[] val = entry.getValue();
if (Bytes.toString(qual).equalsIgnoreCase("account_number")) {
deviceDriverBean.setAccountNo(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("make")) {
deviceDriverBean.setMake(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("model")) {
deviceDriverBean.setModel(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("driver_name")) {
deviceDriverBean.setName(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("premium")) {
deviceDriverBean.setPremium(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("year")) {
deviceDriverBean.setYear(Bytes.toString(val));
} else {
System.out.println("No match found");
}
/*
* System.out.println(Bytes.toString(rowid) + " " +
* Bytes.toString(qual) + " " + Bytes.toString(val));
*/
}
deviceidList.add(deviceDriverBean);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// System.out.println("Message: "+e.getMessage());
e.printStackTrace();
}
return deviceidList;
}
Could this be lazy fetching on the server side by hbase. This means if you return the list hbase won't get a trigger to actually read the list and you will simple get an empty list. I don't know a correct solution, in the past I've seen a similar problem on GAE. This could by solved by simply asking the size of the list just before returning it to the client.
I don't have the exact answer, but I have an advise. In similar situation I put my own trace to check every step in my program.
On the server side before return put : System.out.println("size of table="+deviceidList.size());
You can put this trace in the loop for deviceidList;