Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am currently trying to display a report for out of stock items. I have the function readOutData() implemented into my report activity and it displays all of the products but how can I edit my function to only show products whose quantity is 0? Here is the code for my current function that just reads all of the product data. I added a comment showing what I want it to do, I'm just not sure how to format it.
Cursor readOutData() {
String query = "SELECT * FROM " + TABLE_NAME; //WHERE quantity = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null){
cursor = db.rawQuery(query, null);
}
return cursor;
}
This code should work, assuming that the columns are correct
String query = "SELECT * FROM " + TABLE_NAME + " WHERE quantity = 0";
Although use of a PreparedStatement would be better.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to make a ticket-based support system and I would like to know how to read and delete data from a SQLite table.
The system will work like this:
You click on a reaction and the bot checks if you already have a dedicated channel, if not it will create one.
If you close the ticket by clicking on a reaction in your personal channel, the channel and your data will be deleted.
That's my code so far:
public void onMessageReactionAdd(MessageReactionAddEvent event) {
if(!event.getUser().isBot()) {
if(event.getChannel().getIdLong() == 747412032281772033l && event.getReactionEmote().getEmoji().equals("\uD83C\uDFAB")) {
ResultSet set = LiteSQL.onQuery("SELECT channelid FROM ticketchans WHERE guildid = " + event.getGuild().getIdLong() + " AND userid = " + event.getUserIdLong());
try {
Long user = set.getLong("userid");
if(!(user == event.getUserIdLong())){
Category cat = ((GuildChannel) event.getChannel()).getParent();
TextChannel chan = cat.createTextChannel(event.getMember().getEffectiveName() + "'s TicketChannel").complete();
EmbedBuilder builder = new EmbedBuilder();
builder.setDescription("Hi " + event.getMember().getAsMention() + ", bitte beschreibe hier detailiert dein Anliegen. Wenn du dein ticket schliessen willst klicke auf das X");
builder.setColor(Color.decode("#910cc9"));
chan.sendMessage(builder.build()).queue(Message -> {
Message.addReaction("\u274C").queue();
});
set.next();
LiteSQL.onUpdate("INSERT INTO ticketchans(guildid, channelid, userid) VALUES(" +
event.getGuild().getIdLong() + ", " + event.getChannel().getIdLong() + ", " + event.getUserIdLong() + ")");
event.getChannel().sendMessage(event.getUser().getAsMention() + " TicketChannel eröffnet!").complete().delete().queueAfter(4, TimeUnit.SECONDS);
}
}catch (SQLException e) {}
}
if(event.getReactionEmote().getEmoji().equals("\u274C")) {
//delete data in table event.getGuild().getGuildChannelById(event.getChannel().getIdLong()).delete().reason("").queue();
}
}
}
Getting Data from SQLite
Most of this applies to SQL in general and isn't specific to SQLite.
First off, a SELECT statement consists of different parts.
SELECT columns FROM table WHERE condition;
For columns you have to fill in the names of the columns you want to get from your table. Pretty self-explanatory.
If you want to select more than one column, you just have to list them with commas, like this:
SELECT column1, column2, column3 FROM table WHERE condition;
In order to select every column of your table you just write * instead of the columns.
SELECT * FROM table WHERE condition;
Note: You can only access columns in your ResultSet if you selected them in your statement. If you select channelid you won't be able to get userid, unless you select it as well. (SELECT channelid, userid FROM table WHERE condition;)
You seem to understand the WHERE part so I will skip it. In case you need some more help or want to expand your usage of SQLite even more, you may check out some tutorials online.
Now, after writing your correct SELECT statement it's time to access the data in Java.
Therefore, you have to loop through your ResultSet.
ResultSet rs = LiteSQL.onQuery(
"SELECT channelid, userid
FROM ticketchans
WHERE guildid = " + event.getGuild().getIdLong() + "
AND userid = " + event.getUserIdLong()
);
// loop through the result set
while (rs.next()) {
Long userid = rs.getLong("userid");
Long channelid = rs.getLong("channelid");
}
You now have the data you need and can use it for whatever you want.
Deleting Data from SQLite
Most of this applies to SQL in general and isn't specific to SQLite.
The DELETE statement has a similar structure to the SELECT statement although it lacks the columns (of course).
DELETE FROM table WHERE condition;
As explained in the first part, you have to choose the table you want to delete data from and then narrow it down using conditions.
In your case, deleting a specific ticket would be like this:
DELETE FROM ticketchans WHERE guildid = GID and userid = UID and channelid = CID;
If you don't use all three IDs in the condition, you might end up deleting all tickets of a guild or of an user. Since the channelid is always unique you could possibly skip the userid = UID part, but the details are up to you.
As already mentioned, if you want more specific statements or need some variations, check out a tutorial of your liking. (The one provided is just an example, use whatever you are comfortable with.)
On another note: I would advice not using .complete() but .queue() instead.
If you want to know why and how, check out this page.
I need to get a string from my room database and set it as text in a textview i'm using this code in my dao
#Query("SELECT question, question_heat, question_gender FROM questions WHERE question_heat = :heat AND question_gender = :gender" +
" ORDER BY RANDOM() LIMIT 1")
String getQuestion(int heat, int gender);
i just want to get a random question from my question database.I get this error:
error: Not sure how to convert a Cursor to this method's return type String getQuestion(int heat, int gender);
in the build output says the error is in the query
i'm really new in room i was using sqlopenhelper for a while and i don't really know what to do here.
i found some codes in google but they were for lists of data and i want to get just a string.
You must select only question column. Try this way:
#Query("SELECT question FROM questions WHERE question_heat = :heat AND question_gender = :gender ORDER BY RANDOM() LIMIT 1")
String getQuestion(int heat, int gender);
You select 3 columns and expect to get a string?
I think you must do this :
#Query("SELECT * FROM questions WHERE question_heat = :heat AND question_gender = :gender" +
" ORDER BY RANDOM() LIMIT 1")
QuestionEntity question(int heat, int gender);
and then convert it manually in repository with
String result = question.getQuestion + question.getQuestionHeat + question.getQuestionGender ;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This function keeps on returning a blank string.
public String getRandomWord() {
int id = (int)(Math.random())*(numberOfRows())+1;
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select word from words where id="+id+"", null );
String s = "";
if (res.moveToFirst())
s = res.getString(res.getColumnIndex("word"));
res.close();
return s;
}
The reason for the returning of a blank string is that res.moveToFirst() is false (so your SQL query result was empty) and the if-block will never get run, and thus s will always keep its initial value of "".
The alternative reason could be that the expression is true, but res.getString(res.getColumnIndex("word")) returns a blank string.
If you want a random row (word) then try using :-
public String getRandomWord() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select word from words order by random() limit 1", null );
String s = "";
if (res.moveToFirst())
s = res.getString(res.getColumnIndex("word"));
res.close();
return s;
}
This does assume that there are rows in the table, if there aren't then you'd still get a blank result.
I am used to developing desktop applications with Java. Now I am trying Codename One to develop my first mobile app.
Trying to replicate my experiences with SQL databases I am running into a very odd storage behavior, which I cannot explain.
The database is created, but when I change the table input value, the new value gets ignored and just the old value is added. To save the new value, I have to delete the database.
I like the interface and any kind help would be appreciated.
Database db = Display.getInstance().openOrCreate("MyDB.db");
db.execute("CREATE TABLE IF NOT EXISTS Persons (Date NOT NULL,Event NOT NULL)");
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'John', '10000.00' );";
db.execute (sql);
// adds "John" to the database every time I click the button
// then I change the from "John" to "James"
// I am not adding the lines twice, just change the input
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'James', '10000.00' );";
db.execute (sql);
//keeps adding "John" to the database, even though value has been changed to "James"
Cursor cur = db.executeQuery("select * from Persons;");
Row currentRow= cur.getRow();
String dataText = currentRow.getString(0);
while (cur.next()) {
System.out.println(dataText);
}
You're not fetching the next row into dataText in your while() loop, so you're just repeatedly printing out the text from the first row.
It should be:
Cursor cur = db.executeQuery("select * from Persons;");
while (cur.next()) {
Row currentRow = cur.getRow();
String dataText = currentRow.getString("Date");
System.out.println(dataText);
}
If you examine the table with a separate query tool, like PhpMyAdmin, you should see that it contains both rows.
I hope I got the syntax right. I'm not a Java programmer and I got it from a tutorial.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm having a hard time exactly visualizing 'Cursor' functionality in my program. I kind of get the jist of it, but can anyone explain it's functionality in detail?
By Cursor, I mean the Cursor interface.
I can't simply understand the role it plays with anything.
http://developer.android.com/reference/android/database/Cursor.html
A Cursor object is returned from a query on a SQLite database.
It will return all rows that the query returns.
Say you have a table called names in your database database configured as such:
_id _name
1 Space Ghost
2 Zorak
3 Moltar
4 Brak
If you want to get all data from this table and use it, you would do
something like this:
public HashMap<Integer, String> getNames(){
HashMap<Integer, String> data = new HashMap<Integer, String>();
try{
SQLiteOpenHelper helper = new MyOpenDbHelper(context);
SQLiteDatabase db = helper.getReadableDatabase();
String selectQuery = "SELECT * FROM names";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToFirst()){ //make sure you got results, and move to first row
do{
int mID = cursor.getInt(0); //column 0 for the current row
String mName = cursor.getString(1); //column 1 for the current row
data.put(mID, mName);
} while (cursor.moveToNext()); //move to next row in the query result
}
} catch (Exception ex) {
Log.e("MyApp", ex.getMessage());
} finally
{
if (cursor != null) {
cursor.close();
}
if (db != null) {
db.close();
}
}
return data;
}
Usually you will create your own class to extend SQLiteOpenHelper, as such:
public class MyOpenDbHelper extends SQLiteOpenHelper {
//........
}
From Wikipedia
In computer science, a database cursor is a control structure that enables traversal over the records in a database. Cursors facilitate subsequent processing in conjunction with the traversal, such as retrieval, addition and removal of database records. The database cursor characteristic of traversal makes cursors akin to the programming language concept of iterator.
From Here
A cursor is a tool that allows you to iterate the records in a set. It has concepts of order and current record.
From The documentation you pointed yourself
provides random read-write access to the result set returned by a database query.
So don' t think Cursor as a functionality, but as a mean for reaching records in a more efficient way from any database.
Are you reffering to this Cursor usage?
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor points to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();