"no such column: id (code 1): , while compiling: SELECT id ..." - java

Here is my code:
DataBaseAlarm mDbHelper = new DataBaseAlarm(this);
db = mDbHelper.getWritableDatabase();
private static final String SQL_CREATE_ENTRIES="CREATE TABLE IF NOT EXISTS"+TABLE_NAME+" ("+rowid+" INTEGER PRIMARY KEY AUTOINCREMENT, "+Title+TEXT_TYPE+Time+TEXT_TYPE+Date+TEXT_TYPE+Repeat+TEXT_TYPE+Note+" TEXT NOT NULL);";
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
Cursor c = db.query(
"Alarms", // The table to query
cols, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
from=new String[]{"title","note","time","date","repeat","_id"};
to=new int[]{R.id.title_row,R.id.note_row,R.id.time_row,R.id.date_row,R.id.repeat_row};
adapterCursor =new SimpleCursorAdapter(MainActivity.this, R.layout.alarm_row, c, from, to);
l_list.setAdapter(adapterCursor);
ContentValues cv = new ContentValues();
cv.put("title",msg);
cv.put("note",note);
cv.put("time",hour+":"+minute);
cv.put("date",month+"/"+day+"/"+year);
cv.put("Repeat","daily");
db.insert("Alarms",null,cv);
and for some reason I'm getting this error:
Caused by: android.database.sqlite.SQLiteException: no such column: id (code 1): , while compiling: SELECT id, title, time, date, repeat, note FROM Alarms

Take a look at your table creation code:
private static final String SQL_CREATE_ENTRIES="CREATE TABLE IF NOT EXISTS"+TABLE_NAME+" ("+rowid+" INTEGER PRIMARY KEY AUTOINCREMENT, "+Title+TEXT_TYPE+Time+TEXT_TYPE+Date+TEXT_TYPE+Repeat+TEXT_TYPE+Note+" TEXT NOT NULL);";
It's a mess, and it's full of errors.
It should be something like:
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
" (" + rowid + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
Title + " TEXT, " + Time + " TEXT, " + Date + " TEXT, " +
Repeat + " TEXT, " + Note + " TEXT NOT NULL)";
[EDIT]
Also, this
cv.put("date",month+"/"+day+"/"+year);
is not a valid timeString
This one (assuming that year is a 4 character string and month and day are 2 character strings) is:
cv.put("date", year + "-" + month + "-" + day);
For your reference: http://www.sqlite.org/lang_datefunc.html

Related

Error no such column in SQLite when updating rows

I'm trying to update data in rows in my DB, but i catch error that there's no such column (no such column 'Moscow' or another)
This is DBHelper code:
public static final String tableName = "currentWeather";
public static final String KEY_ID = "_id";
public static final String cityName = "city";
public static final String cityTemp = "temperature";
And creating DB:
sqLiteDatabase.execSQL("create table " + tableName + "(" + KEY_ID + "
integer primary key autoincrement,"
+ cityName + " text," + cityTemp + " text, " + " UNIQUE(" + cityName +
"))");
and error shows when i try to execSQl in response:
sqLiteDatabase.execSQL(
"UPDATE " + DBHelper.tableName + " SET " +
DBHelper.cityTemp + "=" +
response.body().getForecastMain().getTemp() + "
WHERE "
+ DBHelper.cityName + "=" + cityName);
I expect to update temperature data in rows by cityName
cityName and response.body().getForecastMain().getTemp() are strings and they should be passed surrounded with single quotes to the sql statement:
sqLiteDatabase.execSQL(
"UPDATE " + DBHelper.tableName + " SET " + DBHelper.cityTemp + "='" + response.body().getForecastMain().getTemp() + "'" +
"WHERE " + DBHelper.cityName + " = '" + cityName + "'"
);
But the recommended and safe way of doing the update is with the use of ContentValues and ? as placeholders for the parameters:
ContentValues cv = new ContentValues();
cv.put(DBHelper.cityTemp, String.valueOf(response.body().getForecastMain().getTemp()));
int rows = sqLiteDatabase.update(
DBHelper.tableName,
cv,
DBHelper.cityName + " = ?",
new String[] {cityName}
);
You can examine the value of the integer variable rows.
If it is 1 this means that 1 row was updated (because cityName is unique) so the update was successful.
I think you have changed column name or add new one (city). So you can fix it by two ways
By uninstall the application from phone
Add column name in upgrade method.
Example:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0");
}
}
The thing is you need to wrap the values after the = sign in single quotations in the UPDATE statement. As for digits they work in both cases.
For example here is the correct syntax
UPDATE currentWeather
SET temperature = 45
WHERE
city = 'Moscow'
But in your code I'm assuming cityName has the value Moscow without the single quotation marks so the converted SQL code will be like this
UPDATE currentWeather
SET temperature = 45
WHERE
city = Moscow
Now the sql interpreter will think Moscow is some database object or column or something and not a literal value. So you need to surround your values in single quotation marks.
Also consider What the data type of response.body().getForecastMain().getTemp() is.
If it's int you have to parse it or something, as the data type of the related column is Text.

Issue deleting row from SQL Table

I'm trying to remove a row from an SQL table using this code below. However, whenever I call this method I get this following error:
android.database.sqlite.SQLiteException: no such column: Plumber (code 1): , while compiling: DELETE FROM service WHERE name = Plumber
public boolean deleteService(String name){
SQLiteDatabase db = this.getWritableDatabase();
boolean result = false;
String query = "SELECT * FROM "
+ TABLE_SERVICE
+ " WHERE "
+ COLUMN_NAME
+ " = \""
+ name
+ "\""
;
Cursor cursor = db.rawQuery(query, null);
if(cursor.moveToFirst()){
String nameStr = cursor.getString(0);
db.delete(TABLE_SERVICE, COLUMN_NAME + " = " + nameStr, null);
cursor.close();
result = true;
}
db.close();
return result;
}
This is my table
public void onCreate(SQLiteDatabase db){
String CREATE_USERS_TABLE = "CREATE TABLE " +
TABLE_SERVICE + "("
+
COLUMN_NAME + " TEXT," +
COLUMN_RATE + " TEXT," +
COLUMN_CATEGORY + " TEXT," + COLUMN_SUBCATEGORY + " TEXT)";
db.execSQL(CREATE_USERS_TABLE);
}
First you're fetching all the rows that in COLUMN_NAME have the value name.
Next you want to delete the 1st of these rows (maybe it's the only one?) because nameStr gets the value of the 1st column which is COLUMN_NAME.
Why are you doing this?
Just execute this statement:
int number = db.delete(TABLE_SERVICE, COLUMN_NAME + " = '" + name + "'", null);
if number gets the value 0 then no rows were deleted, else it gets the number of deleted rows.
delete deletes rows not columns.
If you want to get rid of a column, you need to drop it. The SQL syntax is:
alter table table_service drop column <column_name>;
I don't know how to express this in java with the methods that you are using.
Ensure that your SQL syntax is correct, and that "Plumber" is a string with double quotes. By my experience, these errors are usually caused by an incorrect column or name.
Use this format:
DELETE FROM table_name WHERE condition(s)
SQLite browser can also help you visualize your database.

Sqlite Query with Subquery returns empty

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.

How to write a create table statement for MySQL using Java where the name of the table is a string?

My question is very simple. I just want to know how to write a create Table statement for MySQL using Java statements where the name of the table is a string.
I know how to insert String values as values of the coloumns using Java. I tried it that way but could not do it. I will show you my code:
String table = "CREATE TABLE table_name'" +
"(SL. No INT not NULL AUTO_INCREMENT, " +
" NAME VARCHAR(100), " +
" YEAR INT not NULL, " +
" IMDB INT not NULL)";
Here instead of table_name I want to input a string variable. The variable name is s2.
Now the Insert into table value is as follows:
myStmt.executeUpdate("insert into l1(id,email,usname,pwd)value('"+(i)+"','"+s1+"','"+s2+"','"+s5+"')");
Here s1,s2,s5 are string values. But this method is not working for Create Table and it is showing syntax error. What is the correct code?
You should remove additional ' sign and change name for SL. No column to somethin else so it looks like
String table = "CREATE TABLE table_name" +
"(slno INT not NULL AUTO_INCREMENT, " +
" NAME VARCHAR(100), " +
" YEAR INT not NULL, " +
" IMDB INT not NULL)"
If your table string is correct you can replace table_name with new name for each table with replace method on string or just use function
public static String getCreateTableQuery(String tableName) {
String table = "CREATE TABLE table_name" +
"(slno INT not NULL AUTO_INCREMENT, " +
" NAME VARCHAR(100), " +
" YEAR INT not NULL, " +
" IMDB INT not NULL)";
String createTableWithNewNameQuery = table.replaceFirst("table_name'", tableName);
return createTableWithNewNameQuery;
}

Insertion error into a database table

I'm really struggling to sort some issues inserting time and dates into a table in my database that dosent seem to excist!.
I asked a question on the 'no such table' issue but didn't get an answer that sorted this issue and circumstances have changed.
Really hoping someone can help me as i cant go forward until i solve this.
Edit:
Does the logcat show im trying to insert before creating the table?
Heres my Logcat error:
01-20 23:38:24.128: E/Database(287): Error inserting app_time=00114200T000000Europe/Dublin(0,0,0,-1,0) app_alarm=false app_date=2013-01-24 app_name=gggg app_comments=a app_type=Business
01-20 23:38:24.128: E/Database(287): android.database.sqlite.SQLiteException: no such table: appointmentsTable: , while compiling: INSERT INTO appointmentsTable(app_time, app_alarm, app_date, app_name, app_comments, app_type) VALUES(?, ?, ?, ?, ?, ?);
Is it a case of this data cannot be inserted as there is no table? I have no idea why I cannot create a table. Im also confused as to why the values passed are '?'
Again here is my OnCreate method:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_TEL + " TEXT NOT NULL, " +
KEY_EMAIL + " TEXT NOT NULL, " +
KEY_COMMENTS + " TEXT NOT NULL);"
);
db.execSQL("CREATE TABLE " + DATABASE_TABLEAPP + " (" +
KEY_ROWAPPID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAMEAPP + " TEXT NOT NULL, " +
KEY_TYPEAPP + " TEXT NOT NULL, " +
KEY_TIMEAPP + " TEXT NOT NULL, " +
KEY_DATEAPP + " TEXT NOT NULL, " +
KEY_COMMENTAPP + " TEXT NOT NULL, " +
KEY_ALARM + " BOOLEAN NOT NULL);"
);
}
My insertion method:
public void createAppointmentEntry(String nameApp, String typeApp, Time timeApp, Date dateApp ,String commentApp, Boolean onOrOff) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAMEAPP, nameApp);
cv.put(KEY_TYPEAPP, typeApp);
cv.put(KEY_TIMEAPP, timeApp.toString());
cv.put(KEY_DATEAPP, dateApp.toString());
cv.put(KEY_COMMENTAPP, commentApp);
cv.put(KEY_ALARM, onOrOff);
ourDatabase.insert(DATABASE_TABLEAPP, null, cv);
}
Do you see how you have your data types as " TEXT NOT NULL "? Try changing the "app_time" column to just " TEXT, " and increase the database version. Also, try downloading SQLite Viewer so that you can get a visual idea of what your db actually looks like and if the column exists.

Categories

Resources