No Such Column while compiling DELETE FROM table - sqlite

I am getting an error like "No Such Column while compiling DELETE FROM table".
please help
public String getData() {
String[] columns = new String []{KEY_ROWID, KEY_HEADER, KEY_QUOTE_VALUE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iHeader = c.getColumnIndex(KEY_HEADER);
int iQuote_value = c.getColumnIndex(KEY_QUOTE_VALUE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow)+ "#" +c.getString(iHeader)+ ":" +c.getString(iQuote_value)+ ":";
}
return result;
}
public void deleteEntry(String Deldata1) throws SQLException {
ourDatabase.delete(DATABASE_TABLE, KEY_HEADER + "=" + Deldata1 , null);
}
}
please help me

The Deldata1 variable is probably not initialized to a quoted string.
Print the value of KEY_HEADER and Deldata1 in the deleteEntry function before the delete call.
Atleast one should be the name of a table in the database. The other can be a table name or a quoted string.

Related

Are Guids unique when using a U-SQL Extractor?

As these questions point out, Guid.NewGuid will return the same value for all rows due to the enforced deterministic nature of U-SQL i.e if it's scaled out if an element (vertex) needs retrying then it should return the same value....
Guid.NewGuid() always return same Guid for all rows
auto_increment in U-SQL
However.... the code example in the officials documentation for a User Defined Extractor purposefully uses Guid.NewGuid().
I'm not querying the validity of the answers for the questions above, as they are from an authoritative source (the programme manager for u-sql, so very authoritative!). However, what I'm wondering if the action of using an Extractor means NewGuid can be used as normal? Is it simply within c# expressions in u-sql and User Defined Functions in which NewGuid is unsafe?
[SqlUserDefinedExtractor(AtomicFileProcessing = true)]
public class FullDescriptionExtractor : IExtractor
{
private Encoding _encoding;
private byte[] _row_delim;
private char _col_delim;
public FullDescriptionExtractor(Encoding encoding, string row_delim = "\r\n", char col_delim = '\t')
{
this._encoding = ((encoding == null) ? Encoding.UTF8 : encoding);
this._row_delim = this._encoding.GetBytes(row_delim);
this._col_delim = col_delim;
}
public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output)
{
string line;
//Read the input line by line
foreach (Stream current in input.Split(_encoding.GetBytes("\r\n")))
{
using (System.IO.StreamReader streamReader = new StreamReader(current, this._encoding))
{
line = streamReader.ReadToEnd().Trim();
//Split the input by the column delimiter
string[] parts = line.Split(this._col_delim);
int count = 0; // start with first column
foreach (string part in parts)
{
if (count == 0)
{ // for column “guid”, re-generated guid
Guid new_guid = Guid.NewGuid();
output.Set<Guid>(count, new_guid);
}
else if (count == 2)
{
// for column “user”, convert to UPPER case
output.Set<string>(count, part.ToUpper());
}
else
{
// keep the rest of the columns as-is
output.Set<string>(count, part);
}
count += 1;
}
}
yield return output.AsReadOnly();
}
yield break;
}
}
https://learn.microsoft.com/en-us/azure/data-lake-analytics/data-lake-analytics-u-sql-programmability-guide#use-user-defined-extractors

Cursor inside another cursor in sqlite db

I have the below code where I am using nested cursors. Both of them are not null but I am getting error
"android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0" on the inner cursor.
Cursor cursor3 = null;
Cursor cursor2 = db.getAllFriendsChat();
cursor2.moveToFirst();
while (!cursor2.isAfterLast()) {
String number = cursor2.getString(cursor2.getColumnIndexOrThrow(ChatModel.COLUMN_CHAT_SENT_TO));
cursor3 = db.getName(number);
String name = cursor3.getString(cursor3.getColumnIndexOrThrow(db.KEY_NAME));
db.insertList(name, number);
cursor3.close();
cursor2.moveToNext();
}
cursor2.close();
getName() Method:
public Cursor getName(String phone) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("select * from " + TABLE_STUDENTS + " where phone_number = " + phone, null);
if (c != null) {
c.moveToFirst(); //***I see that this statement is executed.***
}
return c;
}
I am unable to understand where I am doing mistake. Is there a different way to handle nested cursors in sqlite db. Pls help.
Thanks !
rawQuery() never returns null.
To test whether a cursor is empty, you have to check whether moveToFirst() succeeds, or call isAfterLast().

Replacing HashMap with TreeMap

I am trying to replace HashMap used in my code to TreeMap as I need to have the keys sorted.
But just replacing the HashMap declaration with TreeMap is running into various ClassCast exception which were not arising before. I am debugging the code but I cannot follow why is it failing? It fails in the treemap.put(key, value); statement.
private static void insertIntoIndexFile(String datatype, String value, String columnName, String tableName,
long offset) {
// TODO Auto-generated method stub
Map<Object, ArrayList<Long>> index = new TreeMap<Object, ArrayList<Long>>();
Map<Object, ArrayList<Long>> result = new TreeMap<Object, ArrayList<Long>>();
try{
String indexTableFileName = SCHEMA+"."+tableName+"."+columnName+".ndx";
File indexTableFileObject = new File(indexTableFileName);
long indexfileLength = indexTableFileObject.length();
RandomAccessFile indexTableFile = new RandomAccessFile(indexTableFileObject, "rw");
boolean isValuePresent = false;
if(indexfileLength>0){
// returns sucessfully
index = getIndexFileEntries(indexTableFileName, datatype);
// checking if the key exists
Set set1 = index.entrySet();
Iterator iterator1 = set1.iterator();
while(iterator1.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator1.next();
Object key = me2.getKey();
ArrayList<Long> temp = new ArrayList<Long>();
if(key.toString().equals(value)){
System.out.println("Comparing the hashmap value to value " + key.toString());
isValuePresent = true;
temp = (ArrayList<Long>) me2.getValue();
long frequency = temp.get(0);
frequency++;
temp.set(0, frequency);
temp.add(offset);
index.put(key, temp);
break;
}
}
if(isValuePresent == false){
System.out.println("The file has values but this key was not found. Here is the updated hashmap");
ArrayList<Long> temp = new ArrayList<Long>();
temp.add(Long.parseLong("01"));
temp.add(offset);
Object key = (Object)value;
index.put(key,temp); // this line throws error
writeMapToIndexFile(tableName, columnName, datatype, index);
}else{
writeMapToIndexFile(tableName,columnName, datatype, index);
}
}catch(Exception e){
e.printStackTrace();
}
}
Here is the stacktrace :
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
at java.lang.String.compareTo(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at Database.insertIntoIndexFile(Database.java:433)
at Database.insertIntoTable(Database.java:369)
at Database.main(Database.java:1340)
Similar stacktrace for each of short, integer etc. I expect the key to be these datatypes. Therefore I have used Object type to store the keys. But I am not trying to cast them String before inserting into the map.
Is there anything that I am overlooking while replacing a hashmap with treemap. I agree its a very broad question but any help would really be great.
Thanks for your time.

Sqlite Row Number

I have problem with my database row number. My table has 3 columns(ROWID,WORD,DEFINITION) and 3 row. I delete second row and then I try to query same row, my app fails. is this an autoincrement problem? what should I do?
Here is my code;
//Get that function
public String getThat(int id) {
String result= "";
String[] columns = new String[]{KEY_ROWID,KEY_WORD,KEY_DEFINITION};
Cursor c = ourDatabase.query(DB_TABLE, columns, KEY_ROWID +
"=" + id, null, null, null, null,null);
if(c!=null){
c.moveToFirst();
}
result = c.getString(c.getColumnIndex(KEY_DEFINITION));
return result;
}
//delete function
public boolean deleteRecords(long rowId){
return ourDatabase.delete(DB_TABLE, KEY_ROWID +"="+rowId,null)>0;
}
When the query doesn't match anything, a non-null Cursor is returned anyway but it doesn't contain any rows. When you try to access data from a non-existing row an exception is thrown.
Change this
if(c!=null){
c.moveToFirst();
}
result = c.getString(c.getColumnIndex(KEY_DEFINITION));
to something like
if(c.moveToFirst()){
result = c.getString(c.getColumnIndex(KEY_DEFINITION));
}
i.e. check the return value of moveTo..() and only access cursor data if the move succeeded and the cursor points to a valid row.

Convert a string to Decimal(10,2)

how can i convert a string to a Decimal(10,2) in C#?
Take a look at Decimal.TryParse, especially if the string is coming from a user.
You'll want to use TryParse if there's any chance the string cannot be converted to a Decimal. TryParse allows you to test if the conversion will work without throwing an Exception.
You got to be careful with that, because some cultures uses dots as a thousands separator and comma as a decimal separator.
My proposition for a secure string to decimal converstion:
public static decimal parseDecimal(string value)
{
value = value.Replace(" ", "");
if (System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ",")
{
value = value.Replace(".", ",");
}
else
{
value = value.Replace(",", ".");
}
string[] splited = value.Split(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]);
if (splited.Length > 2)
{
string r = "";
for (int i = 0; i < splited.Length; i++)
{
if (i == splited.Length - 1)
r += System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
r += splited[i];
}
value = r;
}
return decimal.Parse(value);
}
The loop is in case that string contains both, decimal and thousand separator
Try:
string test = "123";
decimal test2 = Convert.ToDecimal(test);
//decimal test2 = Decimal.Parse(test);
//decimal test2;
// if (decimal.TryParse(test, out result))
//{ //valid }
//else
//{ //Exception }
labelConverted.Text = test2.toString();
Decimal Examples
Difference between Convert.ToDecimal(string) & Decimal.Parse(string)
Regards

Resources