swap both user input and database to lowercase before comparing - java

I am trying to find a way to "collect all the classes from a selected date to another, managed by a specific teacher", and so far, its going okay. I have used to uppercase to match with a capital letter as the first one in the name... but since some teachers (McGonnagal) for example is having capital letters in her lastname, is there a way to, say , get the input to lowercase, and also transfer the data in the database (McGonnagal) all to lowercase?
So it would always be a match even if the user inserted McGoNNaGal in the program.... anyone got any ideas?`
try {
String lararesNamn = txtLoCLarare.getText();
String LFN = lararesNamn.toUpperCase().charAt(0)+lararesNamn.substring(1);
String datumFrom = txtLoCfom.getText();
String datumTom = txtLoCtom.getText();
String lararesEN = txtLarareEN.getText();
String LEN = lararesEN.toUpperCase().charAt(0)+lararesEN.substring(1);
ArrayList<HashMap<String,String>> listOfClasses = databas.fetchRows("SELECT KURSNAMN FROM KURS JOIN LARARE ON KURSLARARE = LARAR_ID WHERE KURSSTART >= " + "'" + datumFrom + "'" + " AND KURSSLUT <= " + "'" + datumTom + "'" + " AND(LARARE.FORNAMN = " + "'" + LFN + "'" + " AND LARARE.EFTERNAMN = " + "'" + LEN + "'" + ")");
System.out.println(listOfClasses);
JOptionPane.showMessageDialog(null, listOfClasses);
} catch(InfException ex){
System.out.println(ex.getMessage());
}
Best regards!

You can convert the fetched name from SQL DB to lower or upper case. For LOWER case modify your query to.
SELECT KURSNAMN FROM KURS JOIN LARARE ON KURSLARARE = LARAR_ID WHERE KURSSTART >= " + "'" + datumFrom + "'" + " AND KURSSLUT <= " + "'" + datumTom + "'" + " AND(LOWER(LARARE.FORNAMN) = " + "'" + LFN + "'" + " AND LOWER(LARARE.EFTERNAMN) = " + "'" + LEN + "'" + ")"
You can use UPPER function for upper case

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+"'");

Finding exact string using line.contains

Apologies if some of this information comes across as lacking knowledge, just started learning Java.
In this working the user searches for both road and town. The problem being that when searching for something like 'Cabramatta' the result 'Cabramatta West' will also appear in the results.
The format of the information being read is as follows:
William Street^3^3503^Collins Street^Cabramatta West
William Street^3^3503^Collins Street^Cabramatta
while(fileName.hasNext())
{
String line =fileName.nextLine();
{
if(line.contains(suburbInput) && line.contains(roadInput))
{
String tramDetails[] = line.split("\\^");
String crossStreet = tramDetails[0];
String stopNumber = tramDetails[1];
int stopNumberInt = Integer.parseInt(stopNumber);
String trackerID = tramDetails[2];
int trackerIDInt = Integer.parseInt(trackerID);
String roadName = tramDetails[3];
String suburbName = tramDetails[4];
System.out.print("'Suburb': " + suburbName + " 'Road': " + roadName + " 'Cross Street': " + crossStreet + " 'Stop': " + stopNumberInt + " 'Tracker ID': " + trackerIDInt + "\n");
How do I go about getting it to just find results for 'Cabramatta' when it's searched but also find results for 'Cabramatta West' when that's searched?
You're going to have to split up your inputs before your check so you can use .equals instead of .contains.
while(fileName.hasNext())
{
String line =fileName.nextLine();
String tramDetails[] = line.split("\\^");
String suburbName = tramDetails[4];
String roadName = tramDetails[3];
if(suburbName.equals(suburbInput) && roadName.equals(roadInput))
{
String crossStreet = tramDetails[0];
String stopNumber = tramDetails[1];
int stopNumberInt = Integer.parseInt(stopNumber);
String trackerID = tramDetails[2];
int trackerIDInt = Integer.parseInt(trackerID);
System.out.print("'Suburb': " + suburbName
+ " 'Road': " + roadName
+ " 'Cross Street': " + crossStreet
+ " 'Stop': " + stopNumberInt
+ " 'Tracker ID': " + trackerIDInt + "\n");
}
Split before and then just use equals method of the String. Here is a test code:
String line = "William Street^3^3503^Collins Street^Cabramatta West";
String suburbInput = "Cabramatta";
String roadInput = "Collins Street";
String tramDetails[] = line.split("\\^");
String crossStreet = tramDetails[0];
String stopNumber = tramDetails[1];
int stopNumberInt = Integer.parseInt(stopNumber);
String trackerID = tramDetails[2];
int trackerIDInt = Integer.parseInt(trackerID);
String roadName = tramDetails[3];
String suburbName = tramDetails[4];
if (suburbInput.equals(suburbName) && roadInput.equals(roadName))
System.out.print("'Suburb': " + suburbName + " 'Road': " + roadName + " 'Cross Street': " + crossStreet
+ " 'Stop': " + stopNumberInt + " 'Tracker ID': " + trackerIDInt + "\n");
suburbInput = "Cabramatta West";
if (suburbInput.equals(suburbName) && roadInput.equals(roadName))
System.out.print("'Suburb': " + suburbName + " 'Road': " + roadName + " 'Cross Street': " + crossStreet
+ " 'Stop': " + stopNumberInt + " 'Tracker ID': " + trackerIDInt + "\n");
And output:
'Suburb': Cabramatta West 'Road': Collins Street 'Cross Street': William Street 'Stop': 3 'Tracker ID': 3503
Hope this helps!
You could uses String#endsWith() instead of String#contains() for the suburb:
if (line.endsWith(suburbInput) && line.contains(roadInput))
Of course, this is only a band-aid. 'Cabramatta' would still match 'West Cabramatta' The problem is the if (...) statement, as implemented, is only able to find probable matches. You need to parse the line into the exact fields you want to match against, and then test those fields explicitly.
Alternately (sledge hammer approach), you could implement a regular expression matcher that will match everything exactly in one go.

org.postgresql.util.PSQLException: The column index is out of range: 2, number of columns: 1

I have the following code:
String insert = "INSERT INTO " + tableName +
"(" + COLUMNS.TILE_ID + "," + COLUMNS.TILE_DATA + "," +
COLUMNS.TILE_LEVEL + "," + COLUMNS.TILE_COLUMN +
"," + COLUMNS.TILE_ROW +
"," + COLUMNS.TILE_IMAGE_FORMAT + "," + COLUMNS.TILE_SOURCE +
")";
String values = id + ",?" + "," +
tile.getLevel() + "," + tile.computeColumn() + "," +
tile.computeRow() + ",\'" + tile.getFileType().toUpperCase() +
"\'," + "\'" +
tile.getSource() + "\');";
String query = insert + " VALUES (" + values;
System.out.println(query);
PreparedStatement statement = conn.prepareStatement(query);
statement.setBytes(2, tile.getData());
return this.conn.createStatement().executeUpdate(query);
The query value:
INSERT INTO level1 (TILE_ID,TILE_DATA,TILE_LEVEL,TILE_COLUMN,TILE_ROW,TILE_IMAGE_FORMAT,TILE_SOURCE) VALUES (0,?,1,0,0,'JPG','null');
The error I get:
org.postgresql.util.PSQLException: The column index is out of range: 2, number of columns: 1.
My Table:
tile_id bigint NOT NULL,
tile_data bytea,
tile_level smallint,
tile_row integer,
tile_column integer,
tile_image_format image_format,
tile_source character varying(30),
CONSTRAINT level10_pkey PRIMARY KEY (tile_id)
Any ideas?
You haven't posted your stacktrace but your error seems to appear from this:
statement.setBytes(2, tile.getData());
Which is because you have only one parameter to bind to:
INSERT INTO level1 (TILE_ID,TILE_DATA,TILE_LEVEL,TILE_COLUMN,TILE_ROW,TILE_IMAGE_FORMAT,TILE_SOURCE) VALUES (0,?,1,0,0,'JPG','null');
The fact that the parameter is at position 2 in the values list is not what counts. It's the fact that it's the first place holder that matters. So your code should be,
statement.setBytes(1, tile.getData());
Thanks to e4c5 answer, I fixed my code as following:
String insert = "INSERT INTO " + tableName +
"(" + COLUMNS.TILE_ID + "," + COLUMNS.TILE_DATA + "," +
COLUMNS.TILE_LEVEL + "," + COLUMNS.TILE_COLUMN +
"," + COLUMNS.TILE_ROW +
"," + COLUMNS.TILE_IMAGE_FORMAT + "," + COLUMNS.TILE_SOURCE +
")";
String values = id + ",?" + "," +
tile.getLevel() + "," + tile.computeColumn() + "," +
tile.computeRow() + ",\'" + tile.getFileType().toUpperCase() +
"\'," + "\'" +
tile.getSource() + "\');";
String query = insert + " VALUES (" + values;
PreparedStatement statement = conn.prepareStatement(query);
statement.setBytes(1, tile.getData());
int result = statement.executeUpdate();
statement.close();
return result;
The fact that the parameter is at position 2 in the values list is not what counts. It's the fact that it's the first place holder that matters.

Syntax Error: Encountered "RECURRING"

I was trying to write a SQL statement that updates my database with the new information given. When I run the program it gives me an error saying that it has encountered "RECURRING" at line 1, column 401. What does this mean? I've added to the database using this word before, so I don't understand what the issue is. Here's the code...
stmt.executeUpdate("UPDATE \"CUSTOMERS\" SET FIRSTNAME = " + "'" + customer.getFirstName() + "'" + ", LASTNAME = " + "'" + customer.getLastName() + "'" + ", EMAIL = " + "'" + customer.getEmail() + "'" + ", PHONE = " + "'" + customer.getPhone() + "'" + ", ADDRESS = " + "'" + customer.getAddress() + "'" + ", GROUPONNUMBER = " + "'" + customer.getGrouponNumber() + "'" + ", NOTES = " + "'" + customer.getNotes() + "'" + ", ONETIME = " + customer.getOneTime() + ", RECURRING = " + customer.getRecurring()+ ", NONRESPONSIVE = " + customer.getNonResponsive() + " WHERE FIRSTNAME = " + "'" + active.getFirstName() + "'" + " AND LASTNAME = " + "'" + active.getLastName() + "'" + " AND EMAIL = " + "'" + active.getEmail() + "'" + "AND PHONE = " + "'" + active.getPhone() + "'" + "AND ADDRESS = " + "'" + active.getAddress() + "'" + "AND GROUPONNUMBER = " + "'" + active.getGrouponNumber() + "'" + "AND NOTES = " + "'" + active.getNotes() + "'" + " AND ONETIME = " + active.getOneTime() + "AND RECURRING = " + active.getRecurring() + "AND GROUPON = " + active.getGroupon() + "AND NONRESPONSIVE = " + active.getNonResponsive());
I've haven't used SQL too much, so I don't really know what I'm doing to be honest.

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