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.
I have two tables in my database. Those are user and message.
User table contains with,
Userid (Primary key)
UserName
Password columns
Message table contains with,
MessageId (Primary Key)
Userid (Foreign key)
Subject
Message columns
After login user can send a message. So I want to save the above column details in the message table. But when I fill the table, userid is not getting as a foreign key. That column is empty like the following image.
These are my dbHandler code
public void onCreate(SQLiteDatabase db) {
String TABLE_USER_CREATE = "CREATE TABLE "+ UserTable.Users.TABLE_NAME+"("+
UserTable.Users._ID+" INTEGER PRIMARY KEY,"+
UserTable.Users.COLUMN_NAME+" TEXT,"+
UserTable.Users.COLUMN_PASSWORD+ " TEXT,"+
UserTable.Users.COLUMN_TYPE+ " TEXT"+" );";
db.execSQL(TABLE_USER_CREATE);
String TABLE_MESSAGE_CREATE = "CREATE TABLE "+ MessageTable.Messages.TABLE_NAME+"("+
MessageTable.Messages._ID+" INTEGER PRIMARY KEY,"+
MessageTable.Messages.COLUMN_USER+" TEXT,"+
MessageTable.Messages.COLUMN_SUBJECT+ " TEXT,"+
MessageTable.Messages.COLUMN_MESSAGE+" TEXT,"+
" FOREIGN KEY ("+ MessageTable.Messages.COLUMN_USER+") REFERENCES "+ UserTable.Users.TABLE_NAME+"("+ UserTable.Users._ID+"))";
db.execSQL(TABLE_MESSAGE_CREATE);
}
Save message Method:
public long saveMessage(String subjects, String messages){
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MessageTable.Messages.COLUMN_SUBJECT,subjects);
contentValues.put(MessageTable.Messages.COLUMN_MESSAGE,messages);
long newRowId = db.insert(MessageTable.Messages.TABLE_NAME,null,contentValues);
db.close();
return newRowId; }
I'm new to android. Can somebody help me to fix this?
It's NULL because you never set it. Foreign keys aren't magic, they're just a constraint that whatever value you add must be present in the referenced column.
As you also didn't add a NOT NULL constraint, it just adds exactly what you told it to - only the subject and message.
In my app, i'm using subquerys of sqlite, the subquery returns 3 values, its ok, but in the main query, returns empty and i need help in this.
*some parts of variables is in portuguese because i'm brazilian.
public List<Table_Anuncio_Empregador> getAllUser_Empregador() {
SQLiteDatabase db = this.getReadableDatabase();
List<Table_Anuncio_Empregador> anuncios = new ArrayList<Table_Anuncio_Empregador>();
SharedPreferences preferences = context.getSharedPreferences("user_preferences", MODE_PRIVATE);
int user_id = preferences.getInt("user_id_conectado",0);
String selectQuery = "SELECT "+KEY_ID+", "+KEY_IMAGEM_ANUNCIO+", "+KEY_TITULO+", "+KEY_DESCRICAO+", "+KEY_CIDADE
+ " FROM " + TABLE_ANUNCIO_EMPREGADOR
+ " WHERE "+ KEY_ID +" IN (SELECT "+KEY_ANUNCIO_EMPREGADOR_ID+" FROM "+ TABLE_ANUNCIO
+" WHERE "+ KEY_ANUNCIO_PERFIL+" = 'empregador' AND "+ KEY_USER_ID+" = "+user_id+")";
Log.e(LOG, selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
Table_Anuncio_Empregador anuncio = new Table_Anuncio_Empregador();
anuncio.setAnuncio_empregador_id(c.getInt(c.getColumnIndex(KEY_ID)));
anuncio.setImagem_do_anuncio(c.getBlob(c.getColumnIndex(KEY_IMAGEM_ANUNCIO)));
anuncio.setTitulo(c.getString(c.getColumnIndex(KEY_TITULO)));
anuncio.setDescricao(c.getString(c.getColumnIndex(KEY_DESCRICAO)));
anuncio.setCidade(c.getString(c.getColumnIndex(KEY_CIDADE)));
anuncios.add(anuncio);
} while (c.moveToNext());
}
return anuncios;
}
The LOG shows the query as :-
E/Banco_Helper: SELECT ID, Imagem_anuncio, Titulo, Descricao, Cidade FROM Anuncio_empregador WHERE ID IN (SELECT Anuncio_empregado_info_ID FROM Anuncio WHERE Anuncio_perfil = 'empregador' AND User_ID = 2)
The tables are created using :-
private static final String CREATE_TABLE_ANUNCIO =
"CREATE TABLE IF NOT EXISTS " + TABLE_ANUNCIO + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
KEY_USER_ID + " INTEGER NOT NULL," +
KEY_ANUNCIO_PERFIL + " TEXT NOT NULL," +
KEY_ANUNCIO_EMPREGADOR_ID + " INTEGER," +
KEY_ANUNCIO_PRESTADOR_ID + " INTEGER," +
KEY_CREATED_AT + " DATETIME NOT NULL" + ")";
and :-
private static final String CREATE_TABLE_ANUNCIO_EMPREGADOR =
"CREATE TABLE IF NOT EXISTS " + TABLE_ANUNCIO_EMPREGADOR + "(" + KEY_ID + " INTEGER PRIMARY KEY," +
KEY_TITULO + " TEXT NOT NULL," +
KEY_DESCRICAO + " TEXT NOT NULL," +
KEY_BAIRRO + " TEXT NOT NULL," +
KEY_CIDADE + " TEXT NOT NULL," +
KEY_ESTADO + " TEXT NOT NULL," +
KEY_LOCAL_SERVICO + " TEXT NOT NULL," +
KEY_EXIGENCIAS + " TEXT," +
KEY_IMAGEM_ANUNCIO + " BLOB NOT NULL" + ")";
Equating to :-
CREATE TABLE IF NOT EXISTS Anuncio(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
USER_ID INTEGER NOT NULL,
Anuncio_perfil TEXT NOT NULL,
Anuncio_empregado_info_ID INTEGER,
ANUNCIO_PRESTADOR_ID INTEGER,
CREATED_AT DATETIME NOT NULL
);
And :-
CREATE TABLE IF NOT EXISTS Anuncio_empregador (
ID INTEGER PRIMARY KEY,
Titulo TEXT NOT NULL,
Descricao TEXT NOT NULL,
Bairro TEXT NOT NULL,
Cidade TEXT NOT NULL,
Estado TEXT NOT NULL,
Local_Servico TEXT NOT NULL,
Exigencias TEXT,
Imagem_anuncio BLOB NOT NULL
);
I believe that your issue is with the actual data rather then the query.
That is, the following was used to create and populate the two tables and to also run the query (plus some intermediate queries). The result was that the three expected rows were included and that the three rows that should have been excluded were. That is the query in question ran with the expected results.
The following SQL was used :-
DROP TABLE IF EXISTS Anuncio;
CREATE TABLE IF NOT EXISTS Anuncio(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
USER_ID INTEGER NOT NULL,
Anuncio_perfil TEXT NOT NULL,
Anuncio_empregado_info_ID INTEGER,
ANUNCIO_PRESTADOR_ID INTEGER,
CREATED_AT DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
DROP TABLE IF EXISTS Anuncio_empregador;
CREATE TABLE IF NOT EXISTS Anuncio_empregador (
ID INTEGER PRIMARY KEY,
Titulo TEXT NOT NULL,
Descricao TEXT NOT NULL,
Bairro TEXT NOT NULL,
Cidade TEXT NOT NULL,
Estado TEXT NOT NULL,
Local_Servico TEXT NOT NULL,
Exigencias TEXT,
Imagem_anuncio BLOB NOT NULL DEFAULT X'00010203040506070809'
)
;
INSERT INTO Anuncio_empregador
(Titulo,Descricao,Bairro,Cidade,Estado,Local_Servico,Exigencias)
VALUES
('Mr','Albert','Bloggs','something','something else','xxx','xxxx'),
('Mr','Bert','Bloggs','something','something else','xxx','xxxx'),
('Mr','Charlie','Bloggs','something','something else','xxx','xxxx'),
('Mr','Dave','Bloggs','something','something else','xxx','xxxx'),
('Mr','Eddie','Bloggs','something','something else','xxx','xxxx'),
('Mr','Fred','Bloggs','something','something else','xxx','xxxx'),
('Mr','George','Bloggs','something','something else','xxx','xxxx')
;
SELECT * FROM Anuncio_empregador;
INSERT INTO Anuncio
(USER_ID, Anuncio_perfil,Anuncio_empregado_info_ID,ANUNCIO_PRESTADOR_ID)
VALUES
(1,'empregador',1,100),
(2,'empregador',2,100),
(3,'empregador',3,100),
(4,'not an empregador',1,100),
(5,'not an empregador',2,100),
(6,'not an empregador',3,100)
;
SELECT * FROM Anuncio;
SELECT * FROM Anuncio WHERE Anuncio_perfil = 'empregador';
SELECT ID,Imagem_anuncio,Titulo,Descricao,Cidade
FROM Anuncio_empregador
WHERE ID IN
(
SELECT Anuncio_empregado_info_ID
FROM ANUNCIO
WHERE ANUNCIO_PERFIL = 'empregador' AND USER_ID = user_id
)
;
Note that some liberties were taken, like
using the CURRENT_TIMESTAMP and
using X'00010203040506070809'
saving having to repeat these values which would have no impact upon workings of the SQL.
The resultant Anuncio_empregador table being :-
The resultant Anuncio table being :-
i.e. last 3 rows have been set to be excluded according to the clause WHERE ANUNCIO_PERFIL = 'empregador'
The result of the query in Question
SELECT ID,Imagem_anuncio,Titulo,Descricao,Cidade
FROM Anuncio_empregador
WHERE ID IN
(
SELECT Anuncio_empregado_info_ID
FROM ANUNCIO
WHERE ANUNCIO_PERFIL = 'empregador' AND USER_ID = user_id
)
;
being :-
Note changing AND USER_ID = user_id to AND USER_ID = 2 shows just the 1 row for Bert, as expected.
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've got a DatabaseHelper class where I create the tables.
The first table (recordings) is working fine, but the second one is throwing an Exception when I try to work with it (Insert/Select...).
here is my code from the DatabaseHelper:
public void onCreate(SQLiteDatabase db) {
String createTable="CREATE TABLE recordings" +
"(_id INTEGER PRIMARY KEY AUTOINCREMENT," +
" name VARCHAR(255) NOT NULL," +
" datestart VARCHAR(255) NOT NULL" +
")";
String createTable2="CREATE TABLE recording_image" +
"(_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"imageurl VARCHAR(255) NOT NULL," +
"imagetime INTEGER NOT NULL," +
"prot_id INTEGER NOT NULL," +
"FOREIGN KEY(prot_id) REFERENCES recordings(_id) ON DELETE CASCADE" +
")";
db.execSQL(createTable);
db.execSQL(createTable2);
}
the Exception is:
no such table: recording_image.
What could cause this problem?
Yes, try to clear data of the application, and you can also look to the version of the db, If the version of the db you want to create are higher than the current db on the phone you have to delete and create again all the db.
please see : SQLiteOpenHelper
Hope that will help you :)
Problem solved. Just reinstalling the App or changing the Version number of the Database helped.