private static final String CREATE_TABLE_USER = "CREATE TABLE "
+ TABLE_USER + "(" + "id" + " INTEGER PRIMARY KEY," + "username"
+ " TEXT," + "passwort" + " TEXT," + "sportlevel" + " TEXT,"
+ "ziel" + " TEXT," + "alter" + " REAL," + "groesse" + " REAL,"
+ "gewicht" + " REAL," + "zielgewicht" + " REAL,"
+ "koerperfettanteil" + " REAL," + "trainingprowoche" + " REAL"
+ ")";
//create table statement for USERs
You can not use the alter as column name in the SQLite because it is already reserved keyword.
See here for reserved keywords : https://sqlite.org/lang_keywords.html
alter is a sqlite keyword, I do not think it is usable as column name
Related
I would like to know how to query a database based on the amount of mistakes made by a waiter.
The two tables I have are
Employee
String employeeTable = "CREATE TABLE " + EMP_TABLE + " ("
+ ID_EMP + " INTEGER PRIMARY KEY, "
+ FIRST_NAME + " TEXT,"
+ LAST_NAME + " TEXT,"
+ PROFIT + " INTEGER);";
MistakeEmployee
String mistakeTable = "CREATE TABLE " + MISTAKE_TABLE + " ("
+ ID_MISTAKE + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ID_WAITER_MISTAKE + " INTEGER,"
+ ID_ORDER_MISTAKE + " INTEGER,"
+ MISTAKE_TOTAL + " INITGER,"
+ " FOREIGN KEY (" + ID_WAITER_MISTAKE + ") REFERENCES " + EMP_TABLE + "(" + ID_EMP + "), "
+ " FOREIGN KEY (" + ID_ORDER_MISTAKE + ") REFERENCES " + ORDER_TABLE + "(" + ID_ORDER + "));";
I am trying to order the list based on the Employee with the most Mistakes which would be counted in the mistakes table using the ID_WAITER_MISTAKE.
String query = SELECT * , COUNT(Mistake_TABLE.ID_Waiter) as Count
FROM EMP_TABLE
ORDER BY Count DESC
You must join the tables, group by employee and aggregate:
SELECT e.ID_EMP, e.FIRST_NAME, e.LAST_NAME,
COUNT(m.ID_MISTAKE) AS Mistake_Count
FROM employeeTable e LEFT JOIN mistakeTable m
ON m.ID_WAITER_MISTAKE = e.ID_EMP
GROUP BY e.ID_EMP, e.FIRST_NAME, e.LAST_NAME
ORDER BY Mistake_Count DESC, e.ID_EMP
and in Java code you should construct the sql string like this:
String query =
"SELECT e." + ID_EMP + ", e." + FIRST_NAME + ", e." + LAST_NAME + ", " +
"COUNT(m." + ID_MISTAKE + ") AS Mistake_Count " +
"FROM " + EMP_TABLE + "AS e LEFT JOIN " + MISTAKE_TABLE + " AS m " +
"ON m." + m.ID_WAITER_MISTAKE + " = e." + ID_EMP + " " +
"GROUP BY e." + ID_EMP + ", e." + FIRST_NAME + ", e." + LAST_NAME + " " +
"ORDER BY Mistake_Count DESC, e." + ID_EMP ;
I hope there are no typos.
Below is the code which in which there is an error the app contains thousands of line of code so I am putting only the statement which is having a syntax error please see the bracket inserted on delete cascade statement SQLite statement ON DELETE CASCADE and how can I remove this error Any help is appreciated.
#Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
final String SQL_CREATE_CATEGORIES_TABLE = "CREATE TABLE " +
ChaptersTable.TABLE_NAME + "( " +
ChaptersTable._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
ChaptersTable.COLUMN_NAME + " TEXT " +
")";
final String SQL_CREATE_SUBJECTS_TABLE = "CREATE TABLE " +
SubjectsTable.TABLE_NAME + "( " +
SubjectsTable._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
SubjectsTable.COLUMN_NAME + " TEXT " +
")";
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
QuestionsTable.TABLE_NAME + " ( " +
QuestionsTable._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
QuestionsTable.COLUMN_QUESTION + " TEXT, " +
QuestionsTable.COLUMN_OPTION1 + " TEXT, " +
QuestionsTable.COLUMN_OPTION2 + " TEXT, " +
QuestionsTable.COLUMN_OPTION3 + " TEXT, " +
QuestionsTable.COLUMN_ANSWER_NR + " INTEGER, " +
QuestionsTable.COLUMN_DIFFICULTY + " TEXT, " +
QuestionsTable.COLUMN_SUBJECT_ID+ " INTEGER, " +
"FOREIGN KEY(" + QuestionsTable.COLUMN_SUBJECT_ID+ ") REFERENCES " +
SubjectsTable.TABLE_NAME + "(" + SubjectsTable._ID + ")" + "ON DELETE CASCADE" /*(Here im having error)*/
+
QuestionsTable.COLUMN_CHAPTER_ID + " INTEGER, " +
"FOREIGN KEY(" + QuestionsTable.COLUMN_CHAPTER_ID + ") REFERENCES " +
ChaptersTable.TABLE_NAME + "(" + ChaptersTable._ID + ")" + "ON DELETE CASCADE" +
")";
db.execSQL(SQL_CREATE_CATEGORIES_TABLE);
db.execSQL(SQL_CREATE_QUESTIONS_TABLE);
db.execSQL(SQL_CREATE_SUBJECTS_TABLE);
fillCategoriesTable();
fillQuestionsTable();
fillSubjectsTable();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + ChaptersTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + SubjectsTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + QuestionsTable.TABLE_NAME);
onCreate(db);
}
#Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
db.setForeignKeyConstraintsEnabled(true);
}
The correct syntax is to define the foreign keys where you define the column itself and not later:
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
QuestionsTable.TABLE_NAME + " ( " +
QuestionsTable._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
QuestionsTable.COLUMN_QUESTION + " TEXT, " +
QuestionsTable.COLUMN_OPTION1 + " TEXT, " +
QuestionsTable.COLUMN_OPTION2 + " TEXT, " +
QuestionsTable.COLUMN_OPTION3 + " TEXT, " +
QuestionsTable.COLUMN_ANSWER_NR + " INTEGER, " +
QuestionsTable.COLUMN_DIFFICULTY + " TEXT, " +
QuestionsTable.COLUMN_SUBJECT_ID+ " INTEGER " + "REFERENCES " +
SubjectsTable.TABLE_NAME + "(" + SubjectsTable._ID + ") " + "ON DELETE CASCADE," +
QuestionsTable.COLUMN_CHAPTER_ID + " INTEGER " + "REFERENCES " +
ChaptersTable.TABLE_NAME + "(" + ChaptersTable._ID + ") " + "ON DELETE CASCADE" +
")";
or all the foreign keys at the end of the statement:
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
QuestionsTable.TABLE_NAME + " ( " +
QuestionsTable._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
QuestionsTable.COLUMN_QUESTION + " TEXT, " +
QuestionsTable.COLUMN_OPTION1 + " TEXT, " +
QuestionsTable.COLUMN_OPTION2 + " TEXT, " +
QuestionsTable.COLUMN_OPTION3 + " TEXT, " +
QuestionsTable.COLUMN_ANSWER_NR + " INTEGER, " +
QuestionsTable.COLUMN_DIFFICULTY + " TEXT, " +
QuestionsTable.COLUMN_SUBJECT_ID+ " INTEGER, " +
QuestionsTable.COLUMN_CHAPTER_ID + " INTEGER, " +
"FOREIGN KEY(" + QuestionsTable.COLUMN_SUBJECT_ID+ ") REFERENCES " +
SubjectsTable.TABLE_NAME + "(" + SubjectsTable._ID + ") " + "ON DELETE CASCADE," +
"FOREIGN KEY(" + QuestionsTable.COLUMN_CHAPTER_ID + ") REFERENCES " +
ChaptersTable.TABLE_NAME + "(" + ChaptersTable._ID + ") " + "ON DELETE CASCADE" +//here must come '+' to remove syntax errors
")";
My UpdateRow function is not working. Can someone help?
public boolean UpdateRow(String date ,String timeOut) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("UPDATE " + TABLE_NAME + " SET " + COL_3 + "=" + timeOut + "WHERE " + COL_1 + "=" + date);
}
Thanks in advance.
I think the query that you have written is missing a space between WHERE clause and COL_1. The line should be written as follows.
db.execSQL("UPDATE " + TABLE_NAME
+ " SET " + COL_3 + " = " + timeOut
+ " WHERE " + COL_1 + " = " + date
);
Apostrophes around date and space between columns:
db.execSQL("UPDATE " + TABLE_NAME + " SET " + COL_3 + "=" + timeOut + " WHERE " + COL_1 + "='" + date + "'");
If timeOut is TEXT then it needs apostrophes too:
db.execSQL("UPDATE " + TABLE_NAME + " SET " + COL_3 + "='" + timeOut + "' WHERE " + COL_1 + "='" + date + "'");
I have researched other instances of this error all morning but nothing i've tried so far has worked. It could be something obvious as I am quite new to this.
I am trying to return the results of the GET_ALL_INGREDIENTS query. Which I will then put into a 2d array, but you don't need to worry about that. My TABLE_RECIPES table works fine.
SQLiteException: no such table: TABLE_INGREDIENTS (code 1): , while compiling: SELECT INGR...etc....
Which occurs on the last line of this bit of code:
public String[][] getRecipeIngredients(int id) {
String GET_ALL_INGREDIENTS = "SELECT INGREDIENT_NAME, INGREDIENT_QUANTITY, INGREDIENT_UNIT " +
"FROM TABLE_INGREDIENTS " +
"INNER JOIN TABLE_RECIPE_INGREDIENTS ON TABLE_RECIPE_INGREDIENTS.INGREDIENT_ID=TABLE_INGREDIENTS.INGREDIENT_ID " +
"WHERE RECIPE_INGREDIENTS.RECIPE_ID=" + id;
db = new MyDBHandler(mContext);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(GET_ALL_INGREDIENTS, null);
Table Creation:
final String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " +
TABLE_RECIPES + "(" +
RECIPE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
RECIPE_NAME + " TEXT, " +
RECIPE_INSTRUCTIONS + " TEXT " +
")";
final String CREATE_TABLE_INGREDIENTS = "CREATE TABLE IF NOT EXISTS " +
TABLE_INGREDIENTS + "(" +
INGREDIENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
INGREDIENT_NAME + " TEXT NOT NULL UNIQUE " +
")";
final String CREATE_TABLE_RECIPE_INGREDIENTS = "CREATE TABLE IF NOT EXISTS " +
TABLE_RECIPE_INGREDIENTS + "(" +
RECIPE_ID + " INTEGER NOT NULL, " +
INGREDIENT_ID + " INTEGER NOT NULL, " +
INGREDIENT_QUANTITY + " REAL, " +
INGREDIENT_UNIT + " TEXT, " +
"PRIMARY KEY (" + RECIPE_ID + "," + INGREDIENT_ID + "), " +
"FOREIGN KEY (" + RECIPE_ID + ") REFERENCES " + TABLE_RECIPES + "(" + RECIPE_ID + "), " +
"FOREIGN KEY (" + INGREDIENT_ID + ") REFERENCES " + TABLE_INGREDIENTS + "(" + INGREDIENT_ID + ")" +
")";
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_RECIPES);
db.execSQL(CREATE_TABLE_INGREDIENTS);
db.execSQL(CREATE_TABLE_RECIPE_INGREDIENTS);
}
Thank you for reading and I really appreciate any help i can get with this.
TABLE_INGREDIENTS is a variable. It's value is likely not "TABLE_INGREDIENTS" that is a string literal. So you might want to change
"FROM TABLE_INGREDIENTS " +
to
"FROM " + TABLE_INGREDIENTS +
(You have a number of other similar issues in your SQL too.)
I have probed numerous questions and documentation on this error and cannot seem to find where I am going wrong. The error is on this line:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot add or update a child row: a foreign key constraint fails (`flutweets`.`refs`,
CONSTRAINT `refs_ibfk_1` FOREIGN KEY (`id`) REFERENCES `tweets` (`id`))
The database is MySQL, and I am using Workbench to inspect it; I also know that all the database engines are InnoDB and the Row Formats are Compact. I have three tables: tweets, hashtags, and references.
Here is where I create the tables:
tweets Table
Statement stmt = null;
try {
stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE " + TWEETS_TABLE + "("
+ TWEETS_ID + " BIGINT NOT NULL AUTO_INCREMENT,"
+ TWEETS_TIME + " VARCHAR(255),"
+ TWEETS_USER + " VARCHAR(255),"
+ TWEETS_TEXT + " VARCHAR(255) NOT NULL,"
+ TWEETS_LOCATION + " VARCHAR(255),"
+ TWEETS_CITY + " VARCHAR(255),"
+ TWEETS_PROVINCE + " VARCHAR(255),"
+ TWEETS_COUNTRY + " VARCHAR(255),"
+ TWEETS_TIME_ZONE + " VARCHAR(255),"
+ TWEETS_LATITUDE + " DECIMAL(20,16),"
+ TWEETS_LONGITUDE + " DECIMAL(20,16),"
+ "PRIMARY KEY (" + TWEETS_ID + ")"
+ ")");
. . .
hashtags Table
Statement stmt = null;
try {
stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE " + HASHTAG_TABLE + "("
+ HASHTAG_ID + " BIGINT NOT NULL AUTO_INCREMENT,"
+ HASHTAG_TEXT + " VARCHAR(255),"
+ TWEETS_ID + " BIGINT NOT NULL,"
+ "PRIMARY KEY (" + HASHTAG_ID + "),"
+ "FOREIGN KEY (" + TWEETS_ID + ")"
+ "REFERENCES " + TWEETS_TABLE
+ "(" + TWEETS_ID + ")"
+ ")");
. . .
references Table
Statement stmt = null;
try {
stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE " + REF_TABLE + "("
+ REF_ID + " BIGINT NOT NULL AUTO_INCREMENT,"
+ REF_TEXT + " VARCHAR(255),"
+ TWEETS_ID + " BIGINT NOT NULL,"
+ "PRIMARY KEY (" + REF_ID + "),"
+ "FOREIGN KEY (" + TWEETS_ID + ")"
+ "REFERENCES " + TWEETS_TABLE
+ "(" + TWEETS_ID + ")"
+ ")");
Here are the statements I use to insert and the methods to insert them (I am using prepared statements):
/* INITIALIZE PREPARED STATEMENTS */
// Tweets
private static final String TWEETS_INSERT = "INSERT INTO " + TWEETS_TABLE
+ " (" + TWEETS_TIME + ", " + TWEETS_USER + ", " + TWEETS_TEXT + ", " + TWEETS_LOCATION + ", " + TWEETS_CITY + ", " + TWEETS_PROVINCE + ", "
+ TWEETS_COUNTRY + ", " + TWEETS_TIME_ZONE + ", " + TWEETS_LATITUDE + ", " + TWEETS_LONGITUDE + ")"
+ " VALUES(?,?,?,?,?,?,?,?,?,?)";
private PreparedStatement tweetsStatement;
// Hashtags
private static final String HASHTAGS_INSERT = "INSERT INTO " + HASHTAG_TABLE
+ " (" + HASHTAG_TEXT + ", " + TWEETS_ID + ")" + " VALUES(?,?)";
private PreparedStatement hashStatement;
// References
private static final String REF_INSERT = "INSERT INTO " + REF_TABLE
+ " (" + REF_TEXT + ", " + TWEETS_ID + ")" + " VALUES(?,?)";
private PreparedStatement refStatement;
public void insertHashtag(FluTweet tweet, int hashIndex, Integer tweetID) {
// Pull all of the Hashtag's relevant elements.
String hashText = tweet.getHashtag(hashIndex);
try {
hashStatement.setString(1, hashText);
hashStatement.setString(2, tweetID.toString());
//INSERT HASHTAG INTO TABLE
hashStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void insertReference(FluTweet tweet, int referenceIndex, Integer tweetID) {
// Pull all of the Reference's relevant elements.
String refText = tweet.getReference(referenceIndex);
try {
refStatement.setString(1, refText);
refStatement.setString(2, tweetID.toString());
//INSERT REFERENCE INTO TABLE
refStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
I have no idea why this is not working, any help would be much appreciated. Like I said, I have probed numerous other posts and cannot find relevant help.
Background
I found out the answer to my own question. It was never a problem with any of the actual database handling. It turns out, when I was passing the id to be used as the foreign id in hashtags and references, I was getting my id from a counter in the main class; where every new tweet had a number that went with each hashtag and reference for that tweet that would later be used as a foreign key. That foreign key would reference the primary key in the tweets table, which auto increments.
Here was the problem:
It turns out that MySQL is NOT zero-indexed when you auto-increment; where the first value is zero, then one, then two, etc. Instead, it starts at one. So when I tried to reference the primary key with the foreign key, the counter that started at zero for every tweet that I assigned (the foreign key) was being incorrectly matched to the auto incrementing tweet id in the tweets table (primary key).
Therefore, I was always off by one.
I hope this helps anyone that may have a similar issue.
if we didn't set valid child class object primary key value then we can see the MySQLIntegrityConstraintViolationException.if we ignore the primary key value of child class object then based on the configurations set in hibernate pojo/hbm.xml files first level cache(session) will flush it into data base.