This question already has an answer here:
android.database.sqlite.SQLiteException: no such column or name
(1 answer)
Closed yesterday.
CODE:
//creating an sqlite query and setting column names
along with data types.
String query = "CREATE TABLE tableMon (notes TEXT)";
//calling a exec sql method to execute sql query
db.execSQL(query);
//after adding....passing content values to the table
String insert = "INSERT INTO tableMon (notes) VALUES (
" + values + " )";
db.execSQL(insert);
ERROR:
tableMon has no column named notes in "INSERT INTO tableMon (notes) VALUES ( notes=hello )"
I have tried adding and removing spaces near the column name and adding variables instead direct use of table name and column name.
Though! didn't get any expected result.
Your issue is that the value being inserted is non-numeric and thus must be enclosed in single quotes. So:-
String insert = "INSERT INTO tableMon (notes) VALUES ('" + values + "' )";
However, the above code is susceptible to SQL Injection So it would be better to use:-
String insert = "INSERT INTO tableMon (notes) VALUES (?)";
db.execSQL(insert,new String[]{values};
In this case the value will be suitable enclosed when it is bound by SQLite binding.
However, another approach is to use the SQLiteDatabse insert method. This has the advantages that
it builds the underlying SQL, and
binds values,
and returns the rowid of the inserted row or -1 if the row could not be inserted.
In your case you could use:-
ContentValues cv = new ContentValues();
cv.put("notes",values);
long result = db.insert("tableMon",null,cv);
Here is a working demo:-
public class MainActivity extends AppCompatActivity {
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = SQLiteDatabase.openOrCreateDatabase(this.getDatabasePath("example.db").getPath(),null);
db.execSQL("CREATE TABLE IF NOT EXISTS tableMon (notes TEXT)");
String values = "notes=hello";
db.execSQL("INSERT INTO tableMon (notes) VALUES('" + values + "')");
db.execSQL("INSERT INTO tableMon (notes) VALUES(?)",new String[]{values});
ContentValues cv = new ContentValues();
cv.put("notes",values);
db.insert("tableMon",null,cv);
}
}
Note the use of CREATE TABLE IF NOT EXISTS, which will circumvent the error if the table already exists.
The result, via Android Studio's App Inspection ,when installed and run (first time, subsequent runs would add another set of 3 rows):-
i.e. 3 rows have been inserted using each of the fixes.
I would like to ask for some help with my android code. I am trying to develop a quiz app using SQLite.My Database has two Tables. One for Students Information and one for the Questions and answers. Students Information such as Name, Student ID e.c. are inputs through textViews . After taking the Quiz in the Result activity the Score shown up. But i also want this score to be kept in a column COLUMN_SCORE of Student_trable.
I tried to update the table using this method:
`public static void addScore (int StudentScore){
ContentValues cv = new ContentValues();
cv.put(DataContract.StudentTable.COLUMN_SCORE, StudentScore);
Cursor c = db.rawQuery("SELECT * FROM student_info ORDER BY id DESC LIMIT 1 " ,null);
db.update(DataContract.StudentTable.TABLE_NAME1, cv, DataContract.StudentTable.COLUMN_SCORE + "= ?", new String[] {String.valueOf (c)});
db.close();`
but i failed. Any suggestion please?
Here is some more details of my code:
You can use a subquery in the WHERE clause argument of the update() method, so that there is no need for a SELECT query to retrieve the last id:
public static void addScore(int studentScore) {
String table = DataContract.StudentTable.TABLE_NAME1;
String id = DataContract.StudentTable.COLUMN_ID;
ContentValues cv = new ContentValues();
cv.put(DataContract.StudentTable.COLUMN_SCORE, studentScore);
db.update(
table,
cv,
id + " = (SELECT MAX(" + id + ") FROM " + table + ")",
null
);
db.close();
}
I'm facing an issue executing a very long query using spring jdbcTemplate. The query contains multiple DECLARE statements, multiple CREATE temp tables and in the end a SELECT statement which gets data by joining multiple tables as well as DROP statements. When I run this query directly in SQL Management studio, the query runs perfectly fine and returns me the data. However when I run the exact same query using spring's jdbc template there is no data returned.
Edit: I can not post exact query I'm using. But below is the template of how the query may look.
public class SpringJdbcExample{
public static final String sql = "DECLARE "+
"#XYZ DATETIME='1/31/2016', " +
"#ABC UNIQUEIDENTIFIER='', " +
"#var1 VARCHAR (1)='F', " +
"#var2 UNIQUEIDENTIFIER = NULL " +
"DECLARE #id1 INT, #id2 INT, #id3 Int "+
"SELECT #id1=(SELECT id1 FROM table1 WHERE XYZ=#XYZ) "+
"SELECT #id2=(SELECT id2 FROM table2 WHERE ABC=#ABC) " +
"SET NOCOUNT ON "+
"SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED "+
"CREATE TABLE #temp1 (var1 INT, var2 INT, var2 INT, var4 varchar(20) ) "+
"CREATE TABLE #temp2 (var1 INT,var2 INT, var3 DATETIME, var4 varchar(20)) "+
-- More Create temp tables
-- Insert into temp tables from various DB tables
-- single Select statement from temp tables
-- Drop temp tables
"; // end of the string
private JdbcTemplate jdbcTemplate;
public SpringJdbcExample (JdbcTemplate jdbcTemplate){
this.jdbcTemplate = jdbcTemplate;
}
public List<String> getData(){
// MapSqlParameterSource
MapSqlParameterSource params = new MapSqlParameterSource("someParams", "someValues");
jdbcTemplate.query(sql,params);
}
So I'm trying to fetch data from one of my database tables, could you please check this out for me and see if you can spot the error?
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH, null,
SQLiteDatabase.OPEN_READONLY);
Cursor cursor = db.query(TABLE_CLASSES, new String[] { TABLE_C_DAY,
TABLE_C_NAME, TABLE_C_DAY, TABLE_C_LOCATION, TABLE_C_TIMEHR,
TABLE_C_TIMEMIN, TABLE_C_DURATION, TABLE_C_ONETIMEEVENT,
TABLE_C_CTYPE, TABLE_C_OCCURINGWEEK}, TABLE_C_DAY + "=?",
new String[] { String.valueOf(day) }, null, null, null, null);
Okay so DB_PATH is definitely correct. I tried to close the db connection and it works fine so db works fine and exists.
All of the table column names are correct as these were used in onCreate to create the db and that worked fine. I also tried using
db.rawQuery("SELECT * FROM " + TABLE_CLASSES + " WHERE day = ?", new String[] { String.valueOf(day) });
So when I make the query the app stops and I get a Source code not found message in Eclipse. LogCat says that table 'classes' doesn't exist.
I tried the creation code manually and it worked. Here is the code from onCreate(SQLiteDatabase db);
String CREATE_DB_WITH_INIT_VALUES =
"CREATE TABLE %1$s (%4$s TEXT);" +
"INSERT INTO %1$s VALUES('Lecture');" +
"INSERT INTO %1$s VALUES('Lab');" +
"INSERT INTO %1$s VALUES('Tutorial');" +
"INSERT INTO %1$s VALUES('Meeting');" +
"INSERT INTO %1$s VALUES('Examples Class');" +
"CREATE TABLE %2$s (%5$s smallint, %6$s varchar(40), %7$s varchar(10), %8$s smallint, %9$s smallint, %10$s smallint, %11$s boolean, %12$s smallint, %13$s smallint);" +
"INSERT INTO %2$s VALUES(1,'COMP12112 Computation',1.1,9,0,60,'False','Lecture',3);" +
"INSERT INTO %2$s VALUES(1,'COMP16212 Java OOP 2',1.1,11,0,45,'False','Lecture',3);" +
"INSERT INTO %2$s VALUES(1,'COMP18111 Distributed Systems','Unix',13,15,60,'False','Lab',3);" +
"INSERT INTO %2$s VALUES(2,'Tutorial','LF13',15,0,60,'False','Tutorial',3);" +
"INSERT INTO %2$s VALUES(2,'COMP14111 AI','LF31',10,30,60,'False','Lab',3);" +
"CREATE TABLE %3$s (%14$s smallint, %15$s smallint, %16$s TEXT, %17$s date);";
CREATE_DB_WITH_INIT_VALUES = String.format(CREATE_DB_WITH_INIT_VALUES, TABLE_CLASS_TYPES,
TABLE_CLASSES, TABLE_DEADLINES, TABLE_CT_TYPE,
TABLE_C_DAY, TABLE_C_NAME, TABLE_C_LOCATION, TABLE_C_TIMEHR, TABLE_C_TIMEMIN, TABLE_C_DURATION,
TABLE_C_ONETIMEEVENT, TABLE_C_CTYPE, TABLE_C_OCCURINGWEEK,
TABLE_D_TIMEHR, TABLE_D_TIMEMIN, TABLE_D_DTEXT, TABLE_D_DDATE
);
db.execSQL(CREATE_DB_WITH_INIT_VALUES);
This code doesn't crash and all seems fine but then during the query the table can't be found.
Any idea what is wrong?
What you've done is a valid list of SQL statements. The real problem here is that the method execSQL() only allows you the execution of a single sql statement (See documentation here).
If you want to execute multiple statements automatically, I'd write a method that first splits those statements (by the ending semicolon of each one) and then execute each one in a loop, checking for errors in every iteration so that when some sql statement fails, you can throw a SQLException indicating the sql statement that failed. Something like this:
public static void execSQLScript(SQLiteDatabase db, String script) throws SQLException {
String[] statements = script.split(";");
db.beginTransaction();
for(String statement : statements) {
try {
db.execSQL(statement); // Seems like this method already throws a decent exception
}
catch(SQLException e) {
db.endTransaction(); // Rolling back the changes done
throw e;
}
}
db.setTransactionSuccessful(); // Not rolling but commiting changes, since everything went fine.
db.endTransaction();
}
I'm not a SQL expert but I think your trying to do a little too much when creating the tables. I would suggest creating the table and adding any initial data in 2 different steps.
I don't have any initial data in my database but this is what I'm using to create the table:
createTable = "CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_ONE + " TEXT," + COLUMN_TWO + " INTEGER," + COLUMN_THREE + " TEXT," +
COLUMN_FOUR + " TEXT," + COLUMN_FIVE + " TEXT)";
db.execSQL(createTable);
Now in your case after creating the table you can then insert the initial data you want. After
db.execSQL(createTable);
use a ContentValues to add the data you need to the database.
contentValues = new ContentValues();
contentValues.putXXX();
// keep adding data
// the insert method will add the data for you.
SQLiteDatabase.insert(TABLE_NAME, null, contentValues);
I understand the title may sound confusing, but the goal is very clear:
I am building an application that requires two tables: tracks and waypoints.
A user enters the track name via a textfield and the table generates an ID under track_id.
in the waypoints table there is a column called track_id_fk. When the OnLocationChanged() method is called, the longitude and latitude is entered into the table, along with the time.
I want to add the track_id of the newest track entry in the track table to the track_id_fk column in the waypoints table.
I am using the following code:
SQLiteDatabase db = waypoints.getWritableDatabase();
ContentValues waypointvalues = new ContentValues();
waypointvalues.put(LONGITUDE, loc.getLongitude());
waypointvalues.put(LATITUDE, loc.getLatitude());
waypointvalues.put(TIME, System.currentTimeMillis());
waypointvalues.put(TRACK_ID_FK, "last inserted trackid");
db.insertOrThrow(TABLE_NAME, null, waypointvalues);
I am unsure as to what the value should be where "last inserted trackid" is.
Thanks
insertOrThrow Returns the row ID of the newly inserted row, or -1 if an error occurred
SQLiteDatabase db1 = tracks.getWritableDatabase();
ContentValues tracksvalues = new ContentValues();
tracksvalues.put(COL1, '1');
tracksvalues.put(COL2, '2');
Long insertid=db1.insertOrThrow(TABLE_NAME1, null, tracksvalues);
if (insertid!=-1) {
SQLiteDatabase db2 = waypoints.getWritableDatabase();
ContentValues waypointvalues = new ContentValues();
waypointvalues.put(LONGITUDE, loc.getLongitude());
waypointvalues.put(LATITUDE, loc.getLatitude());
waypointvalues.put(TIME, System.currentTimeMillis());
waypointvalues.put(TRACK_ID_FK, insertid);
db2.insertOrThrow(TABLE_NAME2, null, waypointvalues);
}