So... This is my code:
public static final String DATABASE_NAME = "MY_DATABASE";
public static final String DATABASE_TABLE = "MY_TABLE";
public static final int DATABASE_VERSION = 1;
public static final String KEY_CONTENT = "Content";
public static final String KEY_ID = "_id";
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ DATABASE_TABLE + " (" + KEY_ID
+ " integer primary key, " + KEY_CONTENT
+ " text not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c) { context = c; }
public int delete() {
return sqLiteDatabase.delete(DATABASE_TABLE, KEY_ID , null);
}
There is no mistake message in log. Only break when I run it in my phone. I've used a lot of solutions. It does not want to work(((
Could anybody tell, how to delete the last element in my table?
Get the last inserted element with a Select query limited to one element and ordered by id DESC.
You could also loop throught all elements and override datas till the end, but is not that much efficient if your db has a lot of datas.
Finally, you can use
SELECT last_insert_rowid()
just after you insert something and keep the id as a class scoped variable.
https://www.sqlite.org/c3ref/last_insert_rowid.html
Second parameter of SqliteDatabase.delete() method is WHERE clause. You didn't pass to delete() that clause, didn't say what you want to delete. Basically you get this SQL query:
DELETE FROM DATABASE_TABLE WHERE KEY_ID;
#Alexandre Martin gave you several variants how to get last id.
Related
I am getting an SQL exception
java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'as col_7_0_ from locales offerlocal0_ cross join offers offer2_ inner join offer' at line 1
While calling the repository method
#Query("SELECT DISTINCT new com.greenflamingo.staticplus.model.catalog.dto.OfferGet(ol.root.id,ol.title "
+ ",ol.description,dl.name,ol.root.price,ol.root.currency,ol.root.visible,ol.root.images) "
+ "FROM OfferLocale ol,DescriptorLocale dl "
+ "WHERE ol.root.webfront.id = (:webId) AND ol.culture.languageCode = (:langCode) "
+ "AND dl.culture.languageCode = (:langCode) "
+ "AND ol.root.category = dl.root")
Page<OfferGet> findAllWebfrontLocalized(#Param("webId")int webfrontId,#Param("langCode")String langCode,Pageable pageable );
I have narrowed the issue down to the Collection i am trying to pass to constructor (ol.root.images) . Tried with List (it gave me a constructor missmatch) and with Set (had the same error as shown here)
This is the bean i am using
public class OfferGet implements Serializable{
private static final long serialVersionUID = 6942049862208633335L;
private int id;
private String title;
private String shortDescription;
private String price;
private String category;
private boolean visible;
private List<Image> images;
public OfferGet(String title, String category) {
super();
..........
}
public OfferGet() {
super();
}
public OfferGet(int id, String title, String description
, BigDecimal price
,String currency,
boolean visible) {
.........
}
public OfferGet(int id, String title, String description,String category
, BigDecimal price
,String currency,
boolean visible,
Collection<Image> images) {
..........
}
}
I am using java 11, mariaDb and Springboot 2.0.5
Does anyone know why is this happening and if there is any way around it? Any help would be much appreciated, mustache gracias! :D
It's not possible to create an object with the constructor expression that takes a collection as argument.
The result of a SQL query is always a table.
The reason is that identification variables such that they represent instances, not collections.
Additionally you cannot return root.images you must join the OneToMany relationship and then you no longer have a collection but each attribute.
The result of the query will be cartesian product.
This is a correct query:
#Query("SELECT DISTINCT new com.greenflamingo.staticplus.model.catalog.dto.OfferGet(ol.root.id,ol.title "
+ ",ol.description,dl.name,ol.root.price,ol.root.currency,ol.root.visible, image) "
+ "FROM OfferLocale ol,DescriptorLocale dl "
+ "JOIN ol.root.images image
+ "WHERE ol.root.webfront.id = (:webId) AND ol.culture.languageCode = (:langCode) "
+ "AND dl.culture.languageCode = (:langCode) "
+ "AND ol.root.category = dl.root")
So I have a method that allows me to get the id of a certain item by using a name i already have in an SQL Database. How would I go about getting the entire row of information and storing each item in its own variable.
Method that only works with ID
public Cursor getID(String name){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = " SELECT " + COL1 + " FROM " + TABLE_NAME + " WHERE " + COL2 + " = '" + name + "'";
Cursor data = sqLiteDatabase.rawQuery(query, null);
return data;
}
And the method that gets the query and stores the result
Cursor data = mydb2.getID(name);
int itemId= -1;
while(data.moveToNext()){
itemId = data.getInt(0);
}
Using this method below how would i store all of the data in its own variable using this (or any other way to get data of entire row).
public Cursor rowData(String name){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = " SELECT * FROM " + TABLE_NAME + " WHERE " + COL2 + " = '" + name + "'";
Cursor data = sqLiteDatabase.rawQuery(query, null);
return data;
}
I know this might be a dumb question, and I have tried looking at other questions, I have gotten this far I just don't know what to do next (I'm very new to Sq Lite databases and Android development)
You'd use something like :-
Cursor csr = instance_of_yourdbhelper.rowData();
while(csr.moveToNext()) {
long thisItemId = csr.getLong(csr.getColumnIndex(yourdbhelper.COL_1));
String thisName = csr.getString(csr.getColumnIndex(yourdbhelper.COL_2));
// etc for other columns
}
Notes
yourdbhelper is the class for your DatabaseHelper which is the class that extends SQLiteOpenHelper (the assumption is that the above methods are from such a class, as this is a common usage of SQLite)
instance_of_yourdbhelper is the instance of the DatabaseHelper class i.e. you may have yourdbhelper dbhlpr = new yourdbhelper(parameters);, in which case dbhlpr is the instance.
This just overwrites the same variables (thisItemId and thisName) for each row in the cursor, although there is perhaps the likliehood that the rowData method only returns one row.
You will likely encounter fewer errors using the getColumnIndex method as it returns the offset according to the column name. Miscalculated offsets is a frequent cause of problems.
You may wish to handle a no rows returned situation in which case you can use cursor.getCount(), which will return the number of rows in the cursor.
I want to manage (create/delete/update) a table with 18 columns. Normally, for creating table, I use below codes. Is there any smarter way, like putting the column names in an array etc.? How people handle large tables?
Thanks for your help, as always.
private static final String COL1 = "col1";
private static final String COL2 = "col2";
private static final String COL3 = "col3";
........
........
private static final String COL18 = "col18";
public dbhandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ COL1 + " INTEGER PRIMARY KEY," + COL2 + " TEXT,"
+ COL3 + " TEXT," + .............................+ COL18 + " TEXT")";
db.execSQL(CREATE_TABLE);
}
A smarter way doing so is using db4o (database 4 objects). While creating a database like this has the following advantages:
It is purely based on object database.
No such mapping of tables like in sqlite.
Saves time and volume of code.
Reuse objects by saving and retrieving them as many times as you want.
Benefit from Native Queries.
For more info refer to: http://www.sohailaziz.com/2012/09/using-database-for-objects-db4o-in.html
You can make tuples (column name and type), and store these in an Array. In the onCreate you can loop over it and add it to the CREATE_TABLE string.
But unless you are going to change the columns a lot, a simple copy and paste of lines is more than enough.
If you are use the large table the best way is use the SQLiteManager browser. Remaining all operation do in the normal .java file.If you are use 2 or more table use the SQLiteManager plug-in.
I keep getting this error:
"table keyTable has no column named number"
Still pretty new to Android, so no clue why this happens, can anyone spot the error?
This is my Database class:
public class KeyDatabase extends SQLiteOpenHelper {
private static final String database_name = "KeyDatabase.db";
private static final int database_version = 1;
KeyDatabase (Context context){
super(context,database_name,null,database_version);
}
#Override
public void onCreate (SQLiteDatabase db){
db.execSQL("CREATE TABLE " + KeyTableClass.table_name
+ "(" + KeyTableClass.id + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KeyTableClass.number + " TEXT, "
+ KeyTableClass.key + " TEXT);");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS " + KeyTableClass.table_name);
onCreate(db);
}
public long InsertKey (String number, String key){
ContentValues valuesToInsert = new ContentValues();
valuesToInsert.put(KeyTableClass.number, number);
valuesToInsert.put(KeyTableClass.key, key);
SQLiteDatabase sd = getWritableDatabase();
long result = sd.insert(KeyTableClass.table_name, KeyTableClass.number, valuesToInsert);
return result;
}
This is my class for my table:
public class KeyTableClass {
//The name of the table
public static final String table_name = "keyTable";
//The columns of the table
public static String id = "id";
public static String number = "number";
public static String key = "key";
}
Maybe you've edited the DB onCreate but didn't let it re-run?
Try uninstalling/install the App, Or update database_version to =2.
You don't fit the requirements for the insertion :
public long insert (String table, String nullColumnHack, ContentValues values)
Added in API level 1 Convenience method for inserting a row into the
database.
Parameters table the table to insert the row into
nullColumnHack optional; may be null. SQL doesn't allow inserting a
completely empty row without naming at least one column name. If your
provided values is empty, no column names are known and an empty row
can't be inserted. If not set to null, the nullColumnHack parameter
provides the name of nullable column name to explicitly insert a NULL
into in the case where your values is empty. values this map contains
the initial column values for the row. The keys should be the column
names and the values the column values Returns the row ID of the newly
inserted row, or -1 if an error occurred
Could you try to do :
sb.insert(table_name, null, valuesToInsert);
I have two tables in which the second table has a foreign key which is defined as table 1's primary key. Under the add operation how can I reference the newly added table 1 key to use as table 2's foreign key?
// Project Table columns names
private static final String KEY_ID = "id"; // Primary, integer
private static final String KEY_NAME = "name"; // Unique, text
// Images Table column names
private static final String KEY_IM_ID = "id"; // Primary, integer
private static final String IM_URI = "uri"; // text
private static final String PROJ_IMAGE_ID = "proImgId"; // foreign for Projects Table
public void addProject(Project project) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values_PT = new ContentValues(); // PROJECTS TABLE
ContentValues values_IT = new ContentValues(); // IMAGES TABLE
values_PT.put(KEY_NAME, project.getName()); // project name
// does the KEY ID get added on its own?
values_IT.put(IM_URI, project.getURI()); // image uri
values_IT.put(PROJ_IMAGE_ID, ????????);
}
PROJ_IMAGE_ID needs to have KEY_ID's value, however I do not know how retrieve it. Is there a way to do this?
If your ID columns are declared as INTEGER PRIMARY KEY, then they are autoincrementing and will get their value automatically if you don't set them when inserting.
To get the ID of a new record, you have to actually insert the record first; the new ID is the return value of the insert() function.