SQLiteException: near "SELECT": syntax error: - android-sqlite

I am getting this error
android.database.sqlite.SQLiteException: near "SELECT": syntax error: , while compiling: SELECT _id, c_type, s_name, s_numb, user_name, password FROM accounts WHERE SELECT * FROM TableName LIMIT 1 OFFSET 1
Here is the code the code that creates the problem . My intent is to get the ROWID of ith record from the table and then use that ROWID to delete an entry from the table.
public void deleteEntry(long i) {
String[] columns = new String[]{KEY_ROWID, KEY_CTYPE, KEY_SNAME, KEY_SNUMB, KEY_USRN, KEY_PASS};
Cursor cursor = ourDatabase.query(DATABASE_TABLE,columns,"SELECT * FROM " +DATABASE_TABLE+" LIMIT 1 OFFSET "+i, null, null, null, null, null);
if (cursor != null && cursor.moveToFirst())
{
cursor.moveToFirst();
long rowIds = cursor.getLong(0);
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowIds, null);
}
// ourDatabase.delete(DATABASE_TABLE, KEY_SNUMB + "=" + siteNum, null);
//return ourDatabase.insert(DATABASE_TABLE,null,cv);
}

I achieved the result by changing the approach, but as I am learning android and am a beginner I would like to know how to fix the code I mentioned in the question
String[] columns = new String[]{KEY_ROWID, KEY_CTYPE, KEY_SNAME, KEY_SNUMB, KEY_USRN, KEY_PASS};
Cursor cursor = ourDatabase.query(DATABASE_TABLE, null, null, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
cursor.moveToFirst();
for(int x=0;x<i;x++)
{
cursor.moveToNext();
}
long rowIds = cursor.getLong(0);
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowIds, null);
}

Related

H2: counting (with table lock)

I need to implement a counter by prefix and get the current value. Therefore I created a table UPLOAD_ID:
CREATE TABLE UPLOAD_ID
(
COUNTER INT NOT NULL,
UPLOAD_PREFIX VARCHAR(60) PRIMARY KEY
);
Using H2 and a Spring nativeQuery:
#Query(nativeQuery = true, value = MYQUERY)
override fun nextId(#Param("prefix") prefix: String): Long
with MYQUERY being
SELECT COUNTER FROM FINAL TABLE (
USING (SELECT CAST(:prefix AS VARCHAR) AS UPLOAD_PREFIX FOR UPDATE) S FOR UPDATE
ON T.UPLOAD_PREFIX = S.UPLOAD_PREFIX
WHEN MATCHED
THEN UPDATE
SET COUNTER = COUNTER + 1
WHEN NOT MATCHED
THEN INSERT (UPLOAD_PREFIX, COUNTER)
VALUES (S.UPLOAD_PREFIX, 1) );
I'm unable to lock the table to avoid "Unique index or primary key violation" in my test. In MSSQL I can add WITH (HOLDLOCK) T in MERGE INTO UPLOAD_ID WITH (HOLDLOCK) T to solve this issue.
The gist of my test looks like
try { uploadIdRepo.deleteById(prefix) } catch (e: EmptyResultDataAccessException) { }
val startCount = uploadIdRepo.findById(prefix).map { it.counter }.orElseGet { 0L }
val workerPool = Executors.newFixedThreadPool(35)
val nextValuesRequested = 100
val res = (1..nextValuesRequested).toList().parallelStream().map { i ->
workerPool.run {
uploadIdRepo.nextId(prefix)
}
}.toList()
res shouldHaveSize nextValuesRequested // result count
res.toSet() shouldHaveSize nextValuesRequested // result spread
res.max() shouldBeEqualComparingTo startCount + nextValuesRequested
Can I solve this with H2?

Calling a function on insert with JDBC

I have the following function and table in my PostgreSQL database:
CREATE OR REPLACE FUNCTION generate_uid(size INT) RETURNS TEXT AS $$
DECLARE
characters TEXT := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
bytes BYTEA := gen_random_bytes(size);
l INT := length(characters);
i INT := 0;
output TEXT := '';
BEGIN
WHILE i < size LOOP
output := output || substr(characters, get_byte(bytes, i) % l + 1, 1);
i := i + 1;
END LOOP;
RETURN output;
END;
$$ LANGUAGE plpgsql VOLATILE;
create table users
(
userid text primary key default generate_uid(50)
, username varchar (50) not null
, pass varchar (50) not null
, firstname varchar (100) not null
, lastname varchar (100) not null
, email varchar (150) not null
, roleid int not null
, constraint fkrole foreign key(roleid) references userrole(roleid)
);
Then I call on the function in my DAO in JDBC with this block of code:
Account A = new Account();
String sha256hex = Hashing.sha256()
.hashString(password, StandardCharsets.UTF_8)
.toString();
try (Connection conn = CustomClassFactory.getConnection()) {
String sql = "INSERT INTO users (username, pass, firstname, lastname, email, roleid) VALUES (?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, userName);
ps.setString(2, sha256hex);
ps.setString(3, firstName);
ps.setString(4, lastName);
ps.setString(5, email);
ps.setInt(6, roleId);
System.out.println(ps.toString());
int i = ps.executeUpdate(); // <---update not query. this line is what sends the information to the DB
if (i == 0) {
System.out.println("Sorry, database was not updated. Returning to menu");
return null;
}
} catch (SQLException e) {
System.out.println("Sorry, database was not contacted. Bring your developer coffee. In the Insert Statement");
e.printStackTrace();
return null;
}
I am receiving the following error from the Stack Trace:
org.postgresql.util.PSQLException: ERROR: function gen_random_bytes(integer) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Where: PL/pgSQL function generate_uid(integer) line 8 during statement block local variable initialization
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2552)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2284)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:322)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:481)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:401)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:164)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:130)
at dao.AccountDaoImp.CreateAccount(AccountDaoImp.java:35)
at testing.Tester.main(Tester.java:11)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "models.Account.toString()" because the return value of "dao.AccountDaoImp.CreateAccount(String, String, String, String, String, int)" is null
at testing.Tester.main(Tester.java:11)
How do I make sure it sees the function when I create a new user? The function is designed to generate a random string of text to use as a unique ID.
gen_random_bytes is part of the pgcrypto extension.
So run this in your database:
CREATE EXTENSION pgcrypto SCHEMA public;
To make sure you don't have to rely on search_path, you can prefix public to the function call, like in public.gen_random_uuid().

BETWEEN query to return last 2 days records

Error :
Unhandled Exception: DatabaseException(unrecognized token: "'1582268587562" (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM my_table WHERE date BETWEEN '1582095787562' AND '1582268587562) sql 'SELECT * FROM my_table WHERE date BETWEEN '1582095787562' AND '1582268587562' args []}
I'm trying to get records from the last 2 days:
Future<List<Map<String, dynamic>>> queryLastTwoDays() async {
Database db = await instance.database;
DateTime now = DateTime.now();
DateTime twoDaysAgoFromNow = now.subtract(Duration(days: 2));
var today = now.millisecondsSinceEpoch;
var twoDaysAgo = twoDaysAgoFromNow.millisecondsSinceEpoch;
return await db.rawQuery('''SELECT * FROM $table WHERE $columnDate BETWEEN '$twoDaysAgo' AND '$today''');
}
Structure :
CREATE TABLE $table (
$columnId INTEGER PRIMARY KEY,
$columnName TEXT NOT NULL,
$columnAge INTEGER NOT NULL,
$columnColour TEXT NOT NULL,
$columnDate INTEGER NOT NULL
)
Data :
DatabaseHelper.columnName : 'Breakfast',
DatabaseHelper.columnAge : 23,
DatabaseHelper.columnColour : 'red',
DatabaseHelper.columnDate : DateTime.now().millisecondsSinceEpoch,
As Shawn points out in the comment, your generated SQL is missing a closing quote. Look at the error message:
...while compiling: SELECT * FROM my_table
WHERE date BETWEEN '1582095787562' AND '1582268587562)
There is no closing ' before the parenthesis.
It's coming from this line, I think:
return await db.rawQuery('''SELECT * FROM $table WHERE $columnDate BETWEEN '$twoDaysAgo' AND '$today''');
You need one more single-quote before the triple-single-quote.

E/SQLiteDatabase﹕ Error inserting ,table accounts has no column named control_type (code 1):

tHis is my code for create a db table
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + KEY_CTRL_TYPE + " TEXT,"
+ KEY_USER_NAME + " TEXT,"+ KEY_PASSWORD + " TEXT "
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
and this is for add a contact
void addContact(Accounts accounts) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, accounts.getName()); // Contact Name
values.put(KEY_PH_NO, accounts.getPhoneNumber()); // Contact Phone
values.put(KEY_CTRL_TYPE, accounts.getControlType()); //
values.put(KEY_USER_NAME, accounts.getUserName()); //
values.put(KEY_PASSWORD, accounts.getPassword()); //
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
I am getting this error on accessing addContact
db.addContact(new Accounts(siteName,siteNum,ctype,username,pass));
29206-29206/com.atrolabe.tcpremote1 E/SQLiteDatabase﹕ Error inserting control_type=SHAULA 720 user_name=wetyu phone_number=123455566 password=fhhchhjh name=test
android.database.sqlite.SQLiteException: table accounts has no column named control_type (code 1): , while compiling: INSERT INTO accounts(control_type,user_name,phone_number,password,name) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
the logcat points to this Line in addcontact
db.insert(TABLE_CONTACTS, null, values);
The problem is actually with the initial onCreate() method. The resulting SQL is constructed improperly and never creates the control_type column. See below:
"CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + KEY_CTRL_TYPE + ...
After the phone number field the TEXT keyword is positioned next to the intended control_type column name; resulting in unexpected SQL. For example (filling in with expected values)
CREATE TABLE Contacts (
ContactID INTEGER PRIMARY KEY, ContactName TEXT,
ContactNumber TEXTcontrol_type ...
To fix this problem, simply re-format your CREATE_CONTACTS_TABLE string properly.

HTML5 Database to verify exist table?

Is there a way to verify whether the table is exist inside the database in HTML5 local database?
I need to create 9 tables, and this method will run when the document ready. If each time the page start, it also calling the same method, will it not be waste of memory? I using it for the mobile device (iPhone).
This is the code:
try{
if(!window.openDatabase){
alert('DB not supported.');
}else{
var shortName = 'abc';
var version = '1.0';
var displayName = 'ABC';
var maxSize = 3145728;
var tableName = ['business', 'politic', 'firstread', 'commentary','features', 'insiderasia', 'management', 'media'];
db = openDatabase(shortName, version, displayName, maxSize);
$.each(tableName, function(theCount, value){
db.transaction(
function(transaction){
transaction.executeSql('CREATE TABLE IF NOT EXISTS '+ value +' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, link TEXT NOT NULL, title TEXT NOT NULL, author TEXT NOT NULL, pubdate TEXT NOT NULL, imgLink TEXT NULL, desc TEXT NOT NULL, day TEXT NOT NULL);');
});
});
}
}catch(e){
if(e == INVALID_STATE_ERR){
console.log('invalid database version.');
}else{
console.log('unknown error ' + e + '.');
}
return;
}
For what you need this? If you worry about that you can recreate table that already exist in your database, you need creating your table with this SQL query:
CREATE TABLE IF NOT EXISTS table_name