I have two tables. TABLE_ADD_SUBSTATION is parent table and TABLE_ADD_FEEDER is child table. I am able to add data in child table in the foreign key which does not even exist in parent table. There is no error while inserting in foreign key. What is wrong here? Am I missing something. I am new to android studio.
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "DATABASE.db";
private static final String TABLE_ADD_SUBSTATION = "ADD_SUBSTATION";
private static final String TABLE_ADD_FEEDER = "ADD_FEEDER";
private static final int DATABASE_VERSION = 3;
public DBHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onConfigure(SQLiteDatabase db) {
db.setForeignKeyConstraintsEnabled(true);
super.onConfigure(db);
}
#Override
public void onCreate(SQLiteDatabase db) {
//table for adding substation
String createAddSubstationTable = "create table " + TABLE_ADD_SUBSTATION
+ "(substationNo INT(5) PRIMARY KEY, substationName VARCHAR(30), type VARCHAR(3), "
+ "serialNo INT(10), dateOfInstallation VARCHAR, totalCapacity INT, circle VARCHAR(10), "
+ "location VARCHAR(20), incomingSubstation int, newFeeder VARCHAR(10), newMeter VARCHAR(10))";
db.execSQL(createAddSubstationTable);
//table for adding feeder
String createAddFeederTable = "create table " + TABLE_ADD_FEEDER
+"(feederNo INT(5) PRIMARY KEY, typeOfConductor VARCHAR(30), conductorCapacity INT(10), incomingLine INT(10), "
+ "outgoingLine INT(10), totalLoad INT(10), totalNoOfConnection INT(10), status INT,"
+ "feederName VARCHAR(30), feederLength INT(10), substationNo INT(5) NOT NULL,"
+ " FOREIGN KEY(substationNo) REFERENCES TABLE_ADD_SUBSTATION(substationNo))";
db.execSQL(createAddFeederTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_ADD_SUBSTATION);
db.execSQL("drop table if exists " + TABLE_ADD_FEEDER);
//create table again
onCreate(db);
}
//function to add a substation into database
public char addSubstationIntoDatabase(int substationNo, String substationName, String type, int serialNo,String dateOfInstallation, int totalCapacity, String circle, String location,
int incomingSubstation){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("substationNo", substationNo);
contentValues.put("substationName",substationName);
contentValues.put("type", type);
contentValues.put("serialNo",serialNo);
contentValues.put("dateOfInstallation", dateOfInstallation);
contentValues.put("totalCapacity",totalCapacity);
contentValues.put("circle", circle);
contentValues.put("location", location);
contentValues.put("incomingSubstation", incomingSubstation);
long result = db.insert(TABLE_ADD_SUBSTATION, null, contentValues);
if(result == -1){
Cursor cursor = db.rawQuery("Select substationNo from ADD_SUBSTATION where substationNo = ?", new String[]{String.valueOf(substationNo)});
if(cursor.getCount()>0)
return 'B';
else return 'C';
}
else
return 'D';
}
//function to add feeder into database
public boolean addFeederIntoDatabase(int feederNo,String feederName, int feederLength, String typeOfConductor,
int conductorCapacity, int incomingLine, int outgoingLine, int totalLoad,
int totalNoOfConnection, int status, int substationNo){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("feederNo", feederNo);
contentValues.put("feederName",feederName);
contentValues.put("feederLength", feederLength);
contentValues.put("typeOfConductor", typeOfConductor);
contentValues.put("conductorCapacity", conductorCapacity);
contentValues.put("incomingLine", incomingLine);
contentValues.put("outgoingLine",outgoingLine);
contentValues.put("totalLoad", totalLoad);
contentValues.put("totalNoOfConnection", totalNoOfConnection);
contentValues.put("status", status);
contentValues.put("substationNo", substationNo);
Log.d("contentValues", String.valueOf(contentValues));
long result = db.insert(TABLE_ADD_FEEDER, null, contentValues);
db.close();
if(result == -1)
return false;
else
return true;
}```
In the method onCreate() you construct the string createAddFeederTable by concatenating sql keywords, table names and column names.
But you use TABLE_ADD_SUBSTATION as the name of the table which is referenced by the column substationNo and this is wrong.
TABLE_ADD_SUBSTATION is a variable and not the table's name.
Change your code to this:
String createAddFeederTable = "create table " + TABLE_ADD_FEEDER
+"(feederNo INT(5) PRIMARY KEY, typeOfConductor VARCHAR(30), conductorCapacity INT(10), incomingLine INT(10), "
+ "outgoingLine INT(10), totalLoad INT(10), totalNoOfConnection INT(10), status INT,"
+ "feederName VARCHAR(30), feederLength INT(10), substationNo INT(5) NOT NULL,"
+ "FOREIGN KEY(substationNo) REFERENCES "
+ TABLE_ADD_SUBSTATION
+ "(substationNo))";
db.execSQL(createAddFeederTable);
After this change, uninstall the app from the device to delete the database and rerun to recreate it.
Also, note that the data types INT(10) and VARCHAR do not actually exist in SQLite, although you can use them.
Instead you should use INTEGER and TEXT.
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.
I have a database created in android studio to save data to . The table is not being created in the database . The error I'm getting is :
03-04 00:55:45.783 25787-25787/com/SQLiteLog: (1) no such table: TableName
03-04 00:55:45.783 25787-25787/com.E/SQLiteDatabase: Error inserting
My code for creating the table is :
#Override
public void onCreate(SQLiteDatabase db) {
db = SQLiteDatabase.openOrCreateDatabase("DB.ad",null);
Log.v(TAG, "*TABLE ");
// create TableName table
db.execSQL(CREATE_TableName_TABLE);
this.checkDataBase();
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {
// database doesn't exist yet.
}
return checkDB != null;
}
I was wondering if anyone can tell me why I am getting this error?
String CREATE_TableName_TABLE = "CREATE TABLE TableNames( " +
"Id INT( 30 ) PRIMARY KEY AUTOINCREMENT, " +
"TagNo TEXT, " +
"Description TEXT, " +
"WeeksGone INTEGER( 10 ) NOT NULL DEFAULT 0 );";
Here is an example how to create your database. First your class should extends from SQLiteOpenHelper
Then use super to SQLiteOpenHelper class with your db name and version,
public YourClassName(Context context) {
super(context, "YourDatabaseName", null, 1); // 1 is the version of the database, after each change in your db you should ++.
}
Then create your table:
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
final String SQL_CREATE_BLABLA_TABLE = "CREATE TABLE " + "TableNameHere" + " (" +
"_id" + " INTEGER PRIMARY KEY," +
"name" + " TEXT NOT NULL);";
sqLiteDatabase.execSQL(SQL_CREATE_BLABLA_TABLE);
}
And finally in case you need to upgrade your db version, because you make any change override the onUpgrade method, in order to create again the table.
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + "TableNameHere");
onCreate(sqLiteDatabase);
}
For more information of how to implement SQLite please read this.
Please review the following types in order to create your table:
1.0 Storage Classes and Datatypes
Each value stored in an SQLite database (or manipulated by the database engine) has one of the following storage classes:
NULL. The value is a NULL value.
INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.
TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE).
BLOB. The value is a blob of data, stored exactly as it was input.
For more information of datatypes please see this link.
So your table should be create like this:
String CREATE_TableName_TABLE = "CREATE TABLE TableNames (Id INTEGER PRIMARY KEY AUTOINCREMENT, TagNo TEXT,
Description TEXT, WeeksGone INTEGER NOT NULL DEFAULT 0 );";
I have the following two tables:
Orders
_id
customer
note
ready
OrderTransactions
_id
orderid(links to orders._id)
product
quantity
What I want to do is delete all OrderTransactions that have an order where ready is equal to "y"
I've seen the join mysql statements to do this, but I don't know how to implement those joins in the mDb.delete statement below
public OrdersDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
private static final String ORDERS_CREATE =
"create table orders (_id integer primary key autoincrement, "
+ "customer text not null, note text not null, export text not null);" ;
private static final String ORDERPRODUCTS_CREATE =
"create table orderproducts (_id integer primary key autoincrement, "
+ "orderid integer not null, product text not null, quantity text not null);";
public boolean deleteOrderProductsAllReady(long orderId) {
return mDb.delete(DATABASE_TABLE_ORDERPRODUCTS, ***criteria***, null) > 0;
}
I think the query should look like this:
DELETE ordtran
FROM OrderProducts AS ordtran
INNER JOIN Orders AS ord
ON ordtran.orderid = ord._id
WHERE [ready="y"]
but I don't know how to put that into the above mDb.delete syntax.
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.