Rewrite SQLite statement SELECT WHERE - Android Eclipse - java

I've written a method that searches the database to find matching lecturers depending on modules. However, when I run this, it saves the same name for all three!
Here is the method:
public List<tableModules> getStudentsLecturers(String mod1, String mod2, String mod3) {
List<tableModules> studentModuleLecturer = new ArrayList<tableModules>();
// Select All Query to find lecturers depending on modules
Log.d("Lecturers", mod1);
Log.d("Lecturers", mod2);
Log.d("Lecturers", mod3);
String selectQuery = "SELECT DISTINCT " + Module_Lecturer + " FROM " + Table2 + " WHERE " + Module_Name + " = \'" + mod1 + "\' OR \'" + mod2 + "\' OR \'" + mod3 + "\'";
Log.d("1", "1");
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tableModules moduleLecturers = new tableModules();
moduleLecturers.modulelecturer = cursor.getString(0);
studentModuleLecturer.add(moduleLecturers);
} while (cursor.moveToNext());
}
// return lecture list
return studentModuleLecturer;
}
Which is then called here in MainActivity.java
List<tableModules> lecturers = db.getStudentsLecturers(mod1, mod2, mod3);
if (!lecturers.isEmpty())
{
for (tableModules session: lecturers)
{
Editor editor = preferences.edit();
//Save lecturers to list
for (int i=0; i < lecturers.size(); i++) {
if (counter == 0)
{
lecturer1 = session.modulelecturer.toString();
editor.putString("lec1", lecturer1);
Log.d("Lecs", "1");
editor.commit();
counter++;
}
if (counter == 1)
{
lecturer2 = session.modulelecturer.toString();
editor.putString("lec2", lecturer2);
Log.d("Lecs", "2");
editor.commit();
counter++;
}
if (counter == 2)
{
lecturer3 = session.modulelecturer.toString();
editor.putString("lec3", lecturer3);
Log.d("Lecs", "3");
editor.commit();
counter++;
}
else
{
Log.d("Lecs", "ERROR");
}
}
I get that I'm saving the same "session.modulelecturer.toString();" to each, but I can't figure out how to alter the SQL method to select all three lecturers for all three seperate modules.

Try replacing
" WHERE " + Module_Name + " = \'" + mod1 + "\' OR \'" + mod2 + "\' OR \'" + mod3 + "\'";
with
" WHERE " + Module_Name + " = '" + mod1 + "' OR " + Module_Name + " = '" + mod2 + "' OR " + Module_Name + " = '" + mod3 + "'";
In practice, you can't say
WHERE ModuleName = 'This' OR 'That'
but you can say
WHERE ModuleName = 'This' OR ModuleName = 'That'
I know it's a drag to rewrite the column name for each possible value, but it's how it works in SQL.
Alternatively, you can write a more compact form:
WHERE ModuleName IN ('This', 'That', '...')
So you query can become:
" WHERE " + Module_Name + " IN ('" + mod1 + "', '" + mod2 + "', '" + mod3 + "')";

Related

Updating SQLite - near "WHERE": syntax error (code 1 SQLITE_ERROR):

I recently added a column to my SQLite database, since adding this column a button which I had which sets the value of one of the database columns to "1" or "0" have now started to crash my application when the button tries to use the updateData(), so I assume thats where my issue is, is in the code or the syntax of the updateData()
Error:
android.database.sqlite.SQLiteException: near "WHERE": syntax error
(code 1 SQLITE_ERROR): , while compiling: UPDATE my_manager SET
location_name = 'blarney stone' , location_county =
'Cork',location_description = 'jj',location_route =
'1',location_position = '2',location_longg = 'null',location_lat =
'null',location_url = 'JJ',location_url2 = 'jj',location_url3 = 'jj',
WHERE location_id = '1'
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method)
Code:
void updateData(String id, String row_id, String name, String county, String description, String
in_route, String position, String lat, String longg, String url, String url2, String url3) {
System.out.println(TABLE_NAME+"; "+row_id +"; "+ name +"; "+ county+"; "+ description+"; " + lat
+"; "+ longg+"; "+ url +"; "+ url2 +"; "+ url3 +"; ");
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL("UPDATE " + "my_manager" + " SET location_name = "+"'"+ name + "' " + ", " +
"location_county = " + "'"+ county + "'"+ "," +
"location_description = " + "'"+ description + "'" + "," +
"location_route = " + "'"+ in_route + "'" + "," +
"location_position = " + "'"+ position + "'" + "," +
"location_longg = " + "'"+ longg + "'" + "," +
"location_lat = " + "'"+ lat + "'" + "," +
"location_url = " + "'"+ url + "'" + "," +
"location_url2 = " + "'"+ url2 + "'" + "," +
"location_url3 = " + "'"+ url3 + "'" + "," + " WHERE location_id = "+"'"+ row_id+"'");
Sorry my friend don't take this as a bad but how about you avoid to much unnecessary "+" if it is possible.
void updateData("UPDATE my_manager SET location_name = '"+ name + "', " +
"location_county = '"+ county + "', " +
"location_description = '"+ description + "'," +
"location_route = '"+ in_route + "', " +
"location_position = '" + position + "', " +
"location_longg = '" + longg + "'," +
"location_lat = '" + lat + "'," +
"location_url = '" + url + "', " +
"location_url2 = '"+ url2 + "', " +
"location_url3 = '"+ url3 + "' WHERE location_id = '"+ row_id+"'");

Moving a row in sqlite (Position column)

So, I am currently using the DragSortListView with a SQLite database. I want to resort my database whenever im dragging an item of the ListView to a new position. Therefore I wrote a piece of code that should manage it. But if I'm moving something from a position below to a higher one, it is strangely sorted. I already looked on this code for hours and asked some friends, but I never found the solution.
Code
Method in the DatabaseHelper
public void moveValues(int from, int to, String sammlung){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
System.out.println(from + " - " + to);
if(from < to){
//This part is working properly
Cursor cursor = sqLiteDatabase.rawQuery("SELECT ID FROM " + TABLE_NAME + " WHERE POSITION IS " + "\"" + from + "\" AND SAMMLUNG IS " + "\"" + sammlung + "\"", null);
for (int i = from+1; i < to+1; i++){
switchPositionValue(i, i-1);
}
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_5, to);
cursor.moveToFirst();
sqLiteDatabase.update(TABLE_NAME, contentValues, "ID=?", new String[]{cursor.getInt(0)+""});
cursor.close();
}else{
//This is the not working part
Cursor cursor = sqLiteDatabase.rawQuery("SELECT ID FROM " + TABLE_NAME + " WHERE POSITION IS " + "\"" + from + "\" AND SAMMLUNG IS " + "\"" + sammlung + "\"", null);
for (int i = from-1; i > to-1; i--){
switchPositionValue(i, i+1);
}
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_5, to);
cursor.moveToFirst();
System.out.println(cursor.getInt(0));
//The next line destroys it. But I dont know how to fix it or what exactly is not working
sqLiteDatabase.update(TABLE_NAME, contentValues, "ID=?", new String[]{cursor.getInt(0)+""});
cursor.close();
}
}
The parameters are:
from: The position it's taken away from
to: The position it's taken to
sammlung: I saving all the items of different collections in one database. So it's only there to sort out only specific items.
Method to change the value of a row with a specific position
public void switchPositionValue(int before, int after){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_5, after);
sqLiteDatabase.update(TABLE_NAME, contentValues, "POSITION=?", new String[]{before+""});
}
Demonstration
So if you've got any idea why its behaving this strange or do know a better approach to moving a row in a database, I would really appreciate your help.
Android other way SQL one (COLUMN_5 is POSITION column)
public void moveValues(int from, int to) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query =
"WITH p(from_position,to_position,max_position,min_position) AS (" +
"SELECT " +
"?," +
"?," +
"(SELECT max(" + COLUMN_5 + ") FROM " + TABLE_NAME + ")," +
"(SELECT min(" + COLUMN_5 + ") FROM " + TABLE_NAME + ")), " +
"updates AS(" +
"SELECT " + TABLE_NAME + ".id," + COLUMN_5 + " AS current, " + COLUMN_5 + " + 1 AS proposed " +
"FROM " + TABLE_NAME + " " +
"WHERE " + COLUMN_5 + " >= (SELECT to_position FROM p) " +
"AND " + COLUMN_5 + " < (SELECT from_position FROM p) " +
"UNION SELECT " + TABLE_NAME + ".id," + COLUMN_5 + " AS current, " + COLUMN_5 + " -1 AS proposed " +
"FROM " + TABLE_NAME + " " +
"WHERE " + COLUMN_5 + " <= (SELECT to_position FROM p) " +
"AND " + COLUMN_5 + " > (SELECT from_position FROM p) " +
"UNION SELECT " + TABLE_NAME + ".id," + COLUMN_5 + ",(SELECT to_position FROM p) " +
"FROM " + TABLE_NAME + " " +
"WHERE " + COLUMN_5 + " = (SELECT from_position FROM p) " +
"AND (SELECT from_position FROM p) <> (SELECT to_position FROM p)" +
"), " +
"finish_updates AS (" +
"SELECT * FROM updates " +
"WHERE max((SELECT from_position FROM p),(SELECT to_position FROM p)) <= (SELECT max_position FROM p) " +
"AND min((SELECT from_position FROM p),(SELECT to_position FROM p)) >= (SELECT min_position FROM p)" +
")" +
"UPDATE " + TABLE_NAME + " SET " + COLUMN_5 + " = " +
"(" +
" SELECT proposed " +
" FROM finish_updates " +
" WHERE finish_updates.id = " + TABLE_NAME + ".id" +
") " +
"WHERE " + TABLE_NAME + ".id IN " +
"(" +
" SELECT id FROM finish_updates" +
");";
SQLiteStatement stmnt = sqLiteDatabase.compileStatement(query);
stmnt.bindLong(1,from);
stmnt.bindLong(2,to);
stmnt.executeUpdateDelete();
}
fiddle test SQL at

Java/UCanAccess Insert not working right

last week we got an assignment at school to develop a web Application for students, so they can use them to organize drives to school. The whole project is focused on project management and not on the programming part.
In my team we decided to make a GWT-Application because were all JAVA-Developers.
On the Server side I'm having trouble with our Microsoft Access DB I need to Insert a given dataset in the database, from the frontend I get an createObject which contains all the Information needed to be Insertet. My method looks like this:
#Override
public void makeOffer(CreateObject createobject) {
SecurityContext securityContext = SecurityContextHolder.getContext();
if(!securityContext.getAuthentication().isAuthenticated()) {
return;
}
String userName = securityContext.getAuthentication().getPrincipal().toString();
String teacher = "n";
if(userName.length() < 3) {
teacher = "y";
}
String sql = "INSERT INTO T_FAHRTEN "
+ "(F_SEATS, F_FREESEATS, F_CAR, F_TIME, F_SMOKE, F_GENDER, F_TEACHER, F_INFOS, F_NAME, F_VORNAME, F_NUMMER, F_MAIL, F_STARTTOWN, F_STARTSTREET, F_STARTPLZ, F_DATE, F_USERNAME)"
+ "Values ("
+ "'" + createobject.getSeats() + "', "
+ "'" + createobject.getFreeSeats() + "', "
+ "'" + createobject.getCar() + "', "
+ "'" + createobject.getTime() + "', "
+ "'" + createobject.getSmoke() + "', "
+ "'" + createobject.getGender() + "', "
+ "'" + teacher + "', "
+ "'" + createobject.getInfo() + "', "
+ "'" + createobject.getName() + "', "
+ "'" + createobject.getVorname() + "', "
+ "'" + createobject.getTelNummer() + "', "
+ "'" + createobject.getEmail()+ "', "
+ "'" + createobject.getStartStadt() + "', "
+ "'" + createobject.getStartStreet() + "', "
+ "'" + createobject.getStartPlz()+ "', "
+ "'" + createobject.getDate() + "', "
+ "'" + userName + "'"
+ ");";
Connection conn = null;
Statement stm = null;
try {
//FIXME
String dbURL = getClass().getResource("Drive2Gether2School1.accdb").getPath();
conn = DriverManager.getConnection("jdbc:ucanaccess://" + dbURL);
stm = conn.createStatement();
stm.executeUpdate(sql);
} catch (SQLException e) {
System.out.println("==> error creating");
e.printStackTrace();
//TODO implement Error Handling
} finally {
try {
if(stm != null) stm.close();
if(conn != null) conn.close();
} catch (SQLException e) {
System.out.println("==> error closing");
//TODO implement Error Handling
}
}
System.out.println("==> offer createt");
}
The Problem is, the data doesnt't get Insertet into the Access DB.
Actual its kinda weird, I have a method which gives me everything from the table and shows it on the Frontend. And If I insert something and then show everything I see the stuff I just insertet, but if I open the Tabel in MS-Access the Inserts are not there.
I already tried conn.commit and conn.setAutoCommit(true) both not helping.

Android - Sqlite - CursorWindowAllocationException

I'm struggling with the following exception:
android.database.CursorWindowAllocationException
android.database.CursorWindow.<init>(CursorWindow.java:104)
android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)
android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:162)
android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:156)
android.database.AbstractCursor.moveToPosition(AbstractCursor.java:161)
android.database.AbstractCursor.moveToFirst(AbstractCursor.java:201)
com.hyperlearning.library.Learning.getTotalScore(Learning.java:301)
...
I have the following code:
public int getTotalScore(String categoryCode, int from, int to) {
int repeat = Options.getInt(activity.getString(R.string.repeat_to_learn_key), 10);
String sql =
"select " +
"sum(w1.enabled*w1.score), " +
"sum((1-w1.enabled)*"+repeat+") " +
"from words1 as w1 " +
"join categories_words1 as cw on cw.word1_id = w1.id " +
"join categories as ct on ct.id = cw.category_id " +
"WHERE ct.name = '" + categoryCode + "' AND cw.position BETWEEN " + from + " AND " + to;
Cursor cursor = db.rawQuery(sql, null);
try {
cursor.moveToFirst(); // *** Line 301 ***
return cursor.getInt(0) + cursor.getInt(1);
} finally {
cursor.close();
}
}
The error occurs mainly on Kindle Fire HD.

Writing the resultset to csv file

I have a method getstaffinfo, which has 3 parameter (var_1, connection, filewriter fw), the var_1 value is read from a text file. So the method will be called as many times based on all the var_1 value passed from text file . approx ( 15000)
public static String getstaffid(String var_1, Connection connection,
FileWriter fw) throws SQLException, Exception
// Create a statement
{
String record = null;
ResultSet rs = null;
Statement stmt = connection.createStatement();
boolean empty = true;
try {
rs = stmt
.executeQuery("select username, firstname, lastname, middlename, street, city, stateorprovince, ziporpostalcode, countryorregion, fax, phone, extension, mobile, pager, title, primaryemail, secondaryemail, officename, description, comments, suspendeddate, userdata, employeeid, createuser, updateuser, createdate, updatedate, employeetype, servicedeskticketnumber, startdate, enddate, manager, businessapprover, technicalapprover, delegate, location, jobcodes, customproperty1, customproperty2, customproperty3, customproperty4, customproperty5, customproperty6, customproperty7, customproperty8, customproperty9, customproperty10 from globalusers where username = '"+ var_1 + "'");
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
ArrayList<String> records = new ArrayList<String>();
while (rs.next()) {
empty = false;
//record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4) + " " + rs.getString(5) + " " + rs.getString(6) + " " + rs.getString(7) + " " + rs.getString(8) + " " + rs.getString(9) + " " + rs.getString(10) + " " + rs.getString(11) + " " + rs.getString(12) + " " + rs.getString(13) + " " + rs.getString(14) + " " + rs.getString(15) + " " + rs.getString(16) + " " + rs.getString(17) + " " + rs.getString(18) + " " + rs.getString(19) + " " + rs.getString(20) + " " + rs.getString(21) + " " + rs.getString(22) + " " + rs.getString(23) + " " + rs.getString(24) + " " + rs.getString(25) + " " + rs.getString(26) + " " + rs.getString(27) + " " + rs.getString(28) + " " + rs.getString(29) + " " + rs.getString(30) + " " + rs.getString(31) + " " + rs.getString(32) + " " + rs.getString(33) + " " + rs.getString(34) + " " + rs.getString(35) + " " + rs.getString(36) + " " + rs.getString(37) + " " + rs.getString(38) + " " + rs.getString(39) + " " + rs.getString(40) + " " + rs.getString(41) + " " + rs.getString(42) + " " + rs.getString(43) + " " + rs.getString(44) + " " + rs.getString(45) + " " + rs.getString(46) + " " + rs.getString(47);
for (int i = 1; i <= columns; i++) {
String value = rs.getString(i);
records.add(value);
}
for (int j = 0; j < records.size(); j++) {
record = records.get(j) + ",";
}
fw.append(record);
}
/*fw.append(rs.getString(1));
fw.append(',');
fw.append(rs.getString(2));
fw.append(',');
fw.append(rs.getString(3));
fw.append('\n'); */
} finally {
fw.flush();
rs.close();
stmt.close();
}
return record;
}
As you can see, am executing a query for 47 values, which could be null or it can have some value.
Then i iterate through this 47 column, take the value and store it to an array list. Then i iterate the array list and write all the values to the string record with comma seperated value. Which is written to a csv file.
But it does not work fine. Any inputs would be appreciated...
You may have already solved the problem. Just let you know that I tried to use your code just now and found the issue was here:
record = records.get(j) + ",";
You should use something like this:
record = record + records.get(j) + ",";
Also change String to StringBuffer will improve the performance.
You didn't write the exact problem you face, but there is one for sure: you never write a line break into the file, so all data gets in one line.
while (rs.next()) {
... // your code, with the for loops
fw.append(record); //writing out the line, from your code
fw.append("\r\n"); //line break -- add this line
} //this is the end of the "while(rs.next())" loop
...

Categories