I created a sql query to delete a row given the rowid. When I run the query there are no errors, however, the row doesn't get deleted.
String query = "DELETE FROM " + TABLE_NAME + " WHERE " + " rowid " + " = " + id;
db.execSQL(query);
Try this:
String query = "DELETE FROM " + TABLE_NAME + " WHERE rowid " + " = '" + id + "'";
db.execSQL(query);
But I personally prefer this way:
if (db.delete(TABLE_NAME, rowid+ " = ?", new String[]{id}) != 0) {
Log.i("row", "Has been deleted");
} else{
Log.i("row", "Has not been deleted");
}
SOLUTION: I used the vacuum function to regenerate the proper rowId. I was previously deleting rows where that rowId didn't exist.
Related
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 read a lot of topics about this problem but most of them were having problem with some complex (at least for me) code;
I have followed the oracle ROWNUM Pseudocolumn guide but when I write
SELECT * FROM " + tableName + "
WHERE ROWNUM < 12;
I get this error:
Unknown column 'ROWNUM' in 'where clause'
I then tried to do like the solution suggested here Select where row number = rownum
but nothing changes.
My code looks like this:
sql = "SELECT C.* "
+ "FROM ( SELECT * "
+ " FROM " + tableName + " ) C "
+ "WHERE C.ROWNUM < 12;";
resultSet = statement.executeQuery(sql);
You can refer http://www.w3schools.com/sql/sql_top.asp.
ROWNUM is used in Oracle. Assuming you are using MySQL as you have tagged your question to MySQL.
You can change ROWNUM with limit clause
SELECT * FROM " + tableName + "
LIMIT 11;
Use the below
sql = ""
+ "SELECT C.*,ROWNUM as RECNUM "
+ "FROM ( "
+ " SELECT * "
+ " FROM " + tableName + " ) C "
+ "WHERE C.RECNUM < 12;";
resultSet = statement.executeQuery(sql);
Try this it will helpful for ur problem:
select * from (select * from " + tableName + ") "WHERE C.ROWNUM < 12;
Try this : [if you use mysql]
sql = ""
+ "SELECT C.* "
+ "FROM ( "
+ " SELECT * "
+ " FROM " + tableName + " ) C "
+ "LIMIT 11;";
resultSet = statement.executeQuery(sql);
For sql server :
SELECT TOP 12 ...
I am a new to SQLite database.This is not a duplicate of any other question. I am inserting rows dynamically into a table which has columns like title, tag, date, location etc. I am showing the remaining days from today to the user in a listview. Now my problem is that, I need to update the remaining days column in sqlite table for each day, so that it gets decremented based on the day. How to update all the rows of that remaining days column at once? And how to decrease/update it based on time? This is what I have tried.
public static final String KEY_REMAINING_DAYS = "remainingdays";
public static final int COL_REMAINING_DAYS = 10;
private static final String DATABASE_CREATE_MY_SQL =
"create table " + MY_TABLE
+ " (" + KEY_ROW_ID + " integer primary key autoincrement, "
+ KEY_TAG + " text not null, "
+ KEY_TITLE + " text not null, "
+ KEY_DATE + " text not null, "
+ KEY_LOCATION + " text not null, "
+ KEY_REMAINING_DAYS + " text not null, "
+ ");";
public void update_days() {
String where = "UPDATE "+ MY_TABLE +" SET " + COL_REMAINING_DAYS + " = " + COL_REMAINING_DAYS-1);
db.rawQuery(where, null);
}
The -1 should be SQL, such:
public void update_days() {
String where = "UPDATE "+ MY_TABLE +" SET " + KEY_REMAINING_DAYS + " = " + KEY_REMAINING_DAYS + "-1" );
db.rawQuery(where, null);
}
So that the resulting query is:
UPDATE <MY_TABLE>
SET <KEY_REMAINING_DAYS> = <KEY_REMAINING_DAYS> -1;
As far as "updating it based on time," you'd do this in a daily alarm, or have a check to see when it's been done last as you enter your app. Look for similar questions regarding AlarmManager on this site.
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.
I am trying to insert a row into a MySQL table and get it's insert ID. I am aware of the MySQL last_insert_id() function, I just cannot seem to get it to work. Currently, I am trying to use a function annotated as a transaction and I am only getting 0 returned. I am using Spring 3.1.
#Transactional (propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
private long insertTransactionRecord
(
int custID,
int porID,
String date,
short crvID
) {
m_template.update ("INSERT INTO " +
" transaction " +
"( " +
" por_id, " +
" cust_id, " +
" trans_date, " +
" crv_id " +
") " +
"VALUES " +
"( " +
" ?, " +
" ?, " +
" ?, " +
" ? " +
")",
new Object[] {
porID,
custID,
date,
crvID
});
return m_template.queryForLong ("SELECT " +
" last_insert_id() " +
"FROM " +
" transaction " +
"LIMIT 1");
}
Use Spring's built-in support for this rather than doing it yourself.
SqlUpdate insert = new SqlUpdate(ds, "INSERT INTO company (name) VALUES (?)");
insert.declareParameter(new SqlParameter(Types.VARCHAR));
insert.setReturnGeneratedKeys(true);
// assuming auto-generated col is named 'id'
insert.setGeneratedKeysColumnNames(new String[] {"id"});
insert.compile();
....
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
insert.update(new Object[]{"test"}, keyHolder);
System.out.println(keyHolder.getKey().longValue());
taken from here http://www.codefutures.com/spring-dao/
public int createCompany(Company company) throws SQLException {
jdbcTemplate.update(
"INSERT INTO company (name) VALUES (?)",
company.getName()
);
return jdbcTemplate.queryForInt( "select last_insert_id()" );
}
if you noticed there's no FROM there
The documentation reveals that the syntax for getting the last insert ID is:
SELECT LAST_INSERT_ID()