Reputation: 149
I'm trying to take some data from my View and make an entry into my SQLite database in my android app.
SQLiteDatabase db = openOrCreateDatabase("SemesterDB", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS Semesters (Session VARCHAR, YearStart INT," +
" MonthStart INT, DayStart INT,YearEnd INT, MonthEnd INT, DayEnd INT )");
//extract session from view
Spinner sessionSpinner = (Spinner) findViewById(R.id.sessionSpinner);
String session = (String) sessionSpinner.getSelectedItem();
//extract start date from view
DatePicker startDatePicker = (DatePicker) findViewById(R.id.semesterStartDate);
int startDay = startDatePicker.getDayOfMonth();
int startMonth = startDatePicker.getMonth();
int startYear = startDatePicker.getYear();
//extract end date from view
DatePicker endDatePicker = (DatePicker) findViewById(R.id.semesterEndDate);
int endDay = startDatePicker.getDayOfMonth();
int endMonth = startDatePicker.getMonth();
int endYear = startDatePicker.getYear();
String sessionName = (String) session+" "+startYear;
db.execSQL("INSERT INTO Semesters VALUES(sessionName,startYear,startMonth,startDay,endYear,endMonth,endDay);");
db.close();
--so when i hard code values into the db.execSQL("INSERT..... line, it works just well but when i try and plug in variables with stored values, it doesnt. Any ideas?
This is for an android 2.3 application being written in eclipse juno.
Upvotes: 1
Views: 4558
Reputation: 1043
Your db.execSQL query would also work with some modification to it.
db.execSQL("INSERT INTO Semesters VALUES(" +
sessionName + "," +
startYear + "," +
startMonth + "," +
startDay + "," +
endYear + "," +
endMonth + ","
endDay + ");");
What wrong you are doing is passing the variables such as startYear etc in double quotes which is treated as String and not its value. So your final query string generated and executed turns out to be
INSERT INTO Semesters VALUES(sessionName,startYear,startMonth,startDay,endYear,endMonth,endDay);
hence it fails, as this is not valid query.
Upvotes: 1
Reputation: 1043
Try this, its much better way of doing insert.
ContentValues cv = new ContentValues();
cv.put("Session" , sessionName);
cv.put("YearStart" , startYear);
cv.put("MonthStart" , startMonth);
cv.put("DayStart" , startDay);
cv.put("YearEnd" , endYear);
cv.put("MonthEnd" , endMonth);
cv.put("DayEnd" , endDay);
long rowID = db.insertOrThrow("Semesters", null, cv);
Also another good practice would be to move all your table names and column names to Constants and referring them using those constants.
Upvotes: 0