Search Results

Search found 186 results on 8 pages for 'autoincrement'.

Page 7/8 | < Previous Page | 3 4 5 6 7 8  | Next Page >

  • How to insert records in master/detail relationship

    - by croceldon
    I have two tables: OutputPackages (master) |PackageID| OutputItems (detail) |ItemID|PackageID| OutputItems has an index called 'idxPackage' set on the PackageID column. ItemID is set to auto increment. Here's the code I'm using to insert masters/details into these tables: //fill packages table for i := 1 to 10 do begin Package := TfPackage(dlgSummary.fcPackageForms.Forms[i]); if Package.PackageLoaded then begin with tblOutputPackages do begin Insert; FieldByName('PackageID').AsInteger := Package.ourNum; FieldByName('Description').AsString := Package.Title; FieldByName('Total').AsCurrency := Package.Total; Post; end; //fill items table for ii := 1 to 10 do begin Item := TfPackagedItemEdit(Package.fc.Forms[ii]); if Item.Activated then begin with tblOutputItems do begin Append; FieldByName('PackageID').AsInteger := Package.ourNum; FieldByName('Description').AsString := Item.Description; FieldByName('Comment').AsString := Item.Comment; FieldByName('Price').AsCurrency := Item.Price; Post; //this causes the primary key exception end; end; end; end; This works fine as long as I don't mess with the MasterSource/MasterFields properties in the IDE. But once I set it, and run this code I get an error that says I've got a duplicate primary key 'ItemID'. I'm not sure what's going on - this is my first foray into master/detail, so something may be setup wrong. I'm using ComponentAce's Absolute Database for this project. How can I get this to insert properly? Update Ok, I removed the primary key restraint in my db, and I see that for some reason, the autoincrement feature of the OutputItems table isn't working like I expected. Here's how the OutputItems table looks after running the above code: ItemID|PackageID| 1 |1 | 1 |1 | 2 |2 | 2 |2 | I still don't see why all the ItemID values aren't unique.... Any ideas?

    Read the article

  • Update "Properties" model when adding a new record in CakePHP

    - by Paul Willy
    Hi, I'm writing an application in CakePHP that, for now, is to be used to make quotes for customers. So Quote is a model. I want to have a separate model/table for something like "Property," which may be used by other models. Each time a user gets to the "Add Quote" action, I basically want to pull a Property called "nextQuoteNumber" or something along those lines, and then automatically increment that property, even if the new Quote isn't saved. So I don't think just using an autoincrement for Quote's id is appropriate here - also, the "quote number" could be different from the row's id. I know this is simple enough to do, but I'm trying to figure out the "proper" CakePHP way of doing it! I'm thinking that I should have a method inside the Property model, say "getProperty($property_name)", which would pull the value to return, and also increment the value... but I'm not sure what the best way of doing that is, or how to invoke this method from the Quotes controller. What should I do? Thanks in advance!

    Read the article

  • Problems when I try to see databases in SQLite

    - by Sabau Andreea
    I created in code a database and two tables: static final String dbName="graficeCirculatie"; static final String ruteTable="Rute"; static final String colRuteId="RutaID"; static final String colRuta="Ruta"; static final String statiaTable="Statia"; static final String colStatiaID="StatiaID"; static final String colIdRuta="IdRuta"; static final String colStatia="Statia"; public DatabaseHelper(Context context) { super(context, dbName, null,33); } public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("CREATE TABLE " + statiaTable + " (" + colStatiaID + " INTEGER PRIMARY KEY , " + colIdRuta + " INTEGER, " + colStatia + " TEXT)"); db.execSQL("CREATE TABLE " + ruteTable + "(" + colRuteId + " INTEGER PRIMARY KEY AUTOINCREMENT, " + colRuta + " TEXT);"); InsertDepts(db); } void InsertDepts(SQLiteDatabase db) { ContentValues cv = new ContentValues(); cv.put(colRuteId, 1); cv.put(colRuta, "Expres8"); db.insert(ruteTable, colRuteId, cv); cv.put(colRuteId, 2); cv.put(colRuta, "Expres2"); db.insert(ruteTable, colRuteId, cv); cv.put(colRuteId, 3); cv.put(colRuta, "Expres3"); db.insert(ruteTable, colRuteId, cv); } Now I want to see tables inputs from command line. I try in this way: C:\Program Files\Android\android-sdk\tools sqlite3 SQLite version 3.7.4 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite sqlite3 graficeCirculatie ... select * from ruteTable; And I got an error: Error: near "squlite3": syntax error. Can someone help me?

    Read the article

  • How to check if two records have a self-referencing relation?

    - by Machine
    Consider the following schema with users and their collegues (friends): Users User: columns: user_id: name: user_id as userId type: integer(8) unsigned: 1 primary: true autoincrement: true first_name: name: first_name as firstName type: string(45) notnull: true last_name: name: last_name as lastName type: string(45) notnull: true email: type: string(45) notnull: true unique: true relations: Collegues: class: User local: invitor foreign: invitee refClass: CollegueStatus equal: true onDelete: CASCADE onUpdate: CASCADE Join table: CollegueStatus: columns: invitor: type: integer(8) unsigned: 1 primary: true invitee: type: integer(8) unsigned: 1 primary: true status: type: enum(8) values: [pending, accepted, denied] default: pending notnull: true Now, let's say I two records, one for the user making a HTTP request (the logged in user), and one record for a user he wants to send a message to. I want to check if these users are collegues. Questions: Does Doctrine have any pre-build functionality to check if two records with with self-relations are related? If not, how would you write a method to check this? Where would you put said method? (In the User-class, UserTable-class etc) I could probably do something like this: public function (User $user1, User $user2) { // Ensure we load collegues if $user1 was fetched with DQL that // doesn't load this relation $collegues = $user1->get('Collegues'); $areCollegues = false; foreach($collegues as $collegue) { if($collegue['userId'] === $user2['userId']) { $areCollegues = true; break; } } return $areCollegues; } But this looks a neither efficient nor pretty. I just feel that it should be solved already for self-referencing relations to be nice to use.

    Read the article

  • How SQLite on Android handles long strings?

    - by Levara
    I'm wondering how Android's implementation of SQLite handles long Strings. Reading from online documentation on sqlite, it said that strings in sqlite are limited to 1 million characters. My strings are definitely smaller. I'm creating a simple RSS application, and after parsing a html document, and extracting text, I'm having problem saving it to a database. I have 2 tables in database, feeds and articles. RSS feeds are correctly saved and retrieved from feeds table, but when saving to the articles table, logcat is saying that it cannot save extracted text to it's column. I don't know if other columns are making problems too, no mention of them in logcat. I'm wondering, since text is from an article on web, are signs like (",',;) creating problems? Is Android automaticaly escaping them, or I have to do that. I'm using a technique for inserting similar to one in notepad tutorial: public long insertArticle(long feedid, String title, String link, String description, String h1,tring h2, String h3, String p, String image, long date) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_FEEDID, feedid); initialValues.put(KEY_TITLE, title); initialValues.put(KEY_LINK, link); initialValues.put(KEY_DESCRIPTION, description ); initialValues.put(KEY_H1, h1 ); initialValues.put(KEY_H2, h2); initialValues.put(KEY_H3, h3); initialValues.put(KEY_P, p); initialValues.put(KEY_IMAGE, image); initialValues.put(KEY_DATE, date); return mDb.insert(DATABASE_TABLE_ARTICLES,null, initialValues); } Column P is for extracted text, h1, h2 and h3 are for headers from a page. Logcat reports only column p to be the problem. The table is created with following statement: private static final String DATABASE_CREATE_ARTICLES = "create table articles( _id integer primary key autoincrement, feedid integer, title text, link text not null, description text," + "h1 text, h2 text, h3 text, p text, image text, date integer);";

    Read the article

  • Need some advice before starting coding my next iPhone app...

    - by Tom
    Hi! I need some advice about how should I start coding something. So here is the context: I've just finished building a CMS that manage a SQLite database. My application will be picking this database and use its content as the application's content. So far it's pretty simple. The application will have a navigation that will browse through various workflows, and once at the end workflow, it'll show contents from the database. A consultation kind a thing, example: Liquids - Juice - Orange Juice - Informations about Orange Juice. For my SQLite transactions, so far I believe I'll be using fmdb. It looks like a great wrapper. Here's a simple schema from one of the database: Workflow: id: { type: integer(3), primary: true, autoincrement: true } workflow_id: { type: integer(1) } name: { type: string(255) } That table's rows will be my navigations. Do you believe I should use a navigation controller? If so, then how could I generate the navigation tree from it? I have a good working knowledge of Objective-C and Foundation framework, but never went too far with it so that is why I'm asking before starting in the wrong direction :) Thanks a lot.

    Read the article

  • iPhone - Using sql database - insert statement failing

    - by Satyam svv
    Hi, I'm using sqlite database in my iphone app. I've a table which has 3 integer columns. I'm using following code to write to that database table. -(BOOL)insertTestResult { NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString* documentsDirectory = [paths objectAtIndex:0]; NSString* dataBasePath = [documentsDirectory stringByAppendingPathComponent:@"test21.sqlite3"]; BOOL success = NO; sqlite3* database = 0; if(sqlite3_open([dataBasePath UTF8String], &database) == SQLITE_OK) { BOOL res = (insertResultStatement == nil) ? createStatement(insertResult, &insertResultStatement, database) : YES; if(res) { int i = 1; sqlite3_bind_int(insertResultStatement, 0, i); sqlite3_bind_int(insertResultStatement, 1, i); sqlite3_bind_int(insertResultStatement, 2, i); int err = sqlite3_step(insertResultStatement); if(SQLITE_ERROR == err) { NSAssert1(0, @"Error while inserting Result. '%s'", sqlite3_errmsg(database)); success = NO; } else { success = YES; } sqlite3_finalize(insertResultStatement); insertResultStatement = nil; } } sqlite3_close(database); return success;} The command sqlite3_step is always giving err as 19. I'm not able to understand where's the issue. Tables are created using following queries: CREATE TABLE [Patient] (PID integer NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,PFirstName text NOT NULL,PLastName text,PSex text NOT NULL,PDOB text NOT NULL,PEducation text NOT NULL,PHandedness text,PType text) CREATE TABLE PatientResult(PID INTEGER,PFreeScore INTEGER NOT NULL,PForcedScore INTEGER NOT NULL,FOREIGN KEY (PID) REFERENCES Patient(PID)) I've only one entry in Patient table with PID = 1 BOOL createStatement(const char* query, sqlite3_stmt** stmt, sqlite3* database){ BOOL res = (sqlite3_prepare_v2(database, query, -1, stmt, NULL) == SQLITE_OK); if(!res) NSLog( @"Error while creating %s => '%s'", query, sqlite3_errmsg(database)); return res;}

    Read the article

  • How do I make a lock that allows only ONE thread to read from the resource ?

    - by mare
    I have a file that holds an integer ID value. Currently reading the file is protected with ReaderWriterLockSlim as such: public int GetId() { _fileLock.EnterUpgradeableReadLock(); int id = 0; try { if(!File.Exists(_filePath)) CreateIdentityFile(); FileStream readStream = new FileStream(_filePath, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(readStream); string line = sr.ReadLine(); sr.Close(); readStream.Close(); id = int.Parse(line); return int.Parse(line); } finally { SaveNextId(id); // increment the id _fileLock.ExitUpgradeableReadLock(); } } The problem is that subsequent actions after GetId() might fail. As you can see the GetId() method increments the ID every single time, disregarding what happens after it has issued an ID. The issued ID might be left hanging (as said, exceptions might occur). As the ID is incremented, some IDs might be left unused. So I was thinking of moving the SaveNextId(id) out, remove it (the SaveNextId() actually uses the lock too, except that it's EnterWriteLock). And call it manually from outside after all the required methods have executed. That brings out another problem - multiple threads might enter the GetId() method before the SaveNextId() gets executed and they might all receive the same ID. I don't want any solutions where I have to alter the IDs after the operation, correcting them in any way because that's not nice and might lead to more problems. I need a solution where I can somehow callback into the FileIdentityManager (that's the class that handles these IDs) and let the manager know that it can perform the saving of the next ID and then release the read lock on the file containing the ID. Essentialy I want to replicate the relational databases autoincrement behaviour - if anything goes wrong during row insertion, the ID is not used, it is still available for use but it also never happens that the same ID is issued. Hopefully the question is understandable enough for you to provide some solutions..

    Read the article

  • What is the fastest way to insert 100 000 records from one database to another?

    - by Pentium10
    I have a mobile application. My client has a large data set ~100.000 records. It's updated frequently. When we sync we need to copy from one database to another. I have attached the second database to the main, and run an insert into table select * from sync.table. This is extremely slow, it takes about 10 minutes I think. I noticed that the journal file gets increased step by step. How can I speed this up? EDITED 1 I have indexes off, and I have journal off. Using insert into table select * from sync.table it still takes 10 minutes. EDITED 2 If I run a query like select id,invitem,invid,cost from inventory where itemtype = 1 order by invitem limit 50 it takes 15-20 seconds. The table schema is: CREATE TABLE inventory ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'serverid' INTEGER NOT NULL DEFAULT 0, 'itemtype' INTEGER NOT NULL DEFAULT 0, 'invitem' VARCHAR, 'instock' FLOAT NOT NULL DEFAULT 0, 'cost' FLOAT NOT NULL DEFAULT 0, 'invid' VARCHAR, 'categoryid' INTEGER DEFAULT 0, 'pdacategoryid' INTEGER DEFAULT 0, 'notes' VARCHAR, 'threshold' INTEGER NOT NULL DEFAULT 0, 'ordered' INTEGER NOT NULL DEFAULT 0, 'supplier' VARCHAR, 'markup' FLOAT NOT NULL DEFAULT 0, 'taxfree' INTEGER NOT NULL DEFAULT 0, 'dirty' INTEGER NOT NULL DEFAULT 1, 'username' VARCHAR, 'version' INTEGER NOT NULL DEFAULT 15 ) Indexes are created like CREATE INDEX idx_inventory_categoryid ON inventory (pdacategoryid); CREATE INDEX idx_inventory_invitem ON inventory (invitem); CREATE INDEX idx_inventory_itemtype ON inventory (itemtype); I am wondering, the insert into ... select * from isn't the fastest built-in way to do massive data copy? EDITED 3 SQLite is serverless, so please stop voting a particular answer, because that is not the answer I'm sure.

    Read the article

  • Why extremely occasionally will one of bof/eof be true for a new non-empty recordset

    - by jjb
    set recordsetname = databasename.openrecordset(SQLString) if recordsetname.bof <> true and recordsetname.eof <> true then 'do something end if 2 questions : the above test can evaluate to false incorrectly but only extremely rarely (I've had one lurking in my code and it failed today, I believe for the first time in 5 years of daily use-that's how I found it). Why very occasionally will one of bof/eof be true for a non-empty recordset. It seems so rare that I wonder why it occurs at all. Is this a foolproof replacement: if recordsetname.bof <> true or recordsetname.eof <> true then Edit to add details of code : Customers have orders, each order begins with a BeginOrder item and end with an EndOrder item and in between are the items in the order. The SQL is: ' ids are autoincrement long integers ' SQLString = "select * from Orders where type = OrderBegin or type = OrderEnd" Dim OrderOpen as Boolean OrderOpen = False Set rs = db.Openrecordset(SQLString) If rs.bof <> True And rs.eof <> True Then myrec.movelast If rs.fields("type").value = BeginOrder Then OrderOpen = True End If End If If OrderOpen F False Then 'code here to add new BeginOrder Item to Orders table ' End If ShowOrderHistory 'displays the customer's Order history ' In this case which looks this this BeginOrder Item a Item b ... Item n EndOrder BeginOrder Item a Item b ... Item n EndOrder BeginOrder Item a item b ... Item m BeginOrder <----should not be there as previous order still open

    Read the article

  • syntax for MySQL INSERT with an array of columns

    - by Mike_Laird
    I'm new to PHP and MySQL query construction. I have a processor for a large form. A few fields are required, most fields are user optional. In my case, the HTML ids and the MySQL column names are identical. I've found tutorials about using arrays to convert $_POST into the fields and values for INSERT INTO, but I can't get them working - after many hours. I've stepped back to make a very simple INSERT using arrays and variables, but I'm still stumped. The following line works and INSERTs 5 items into a database with over 100 columns. The first 4 items are strings, the 5th item, monthlyRental is an integer. $query = "INSERT INTO `$table` (country, stateProvince, city3, city3Geocode, monthlyRental) VALUES ( '$country', '$stateProvince', '$city3', '$city3Geocode', '$monthlyRental')"; When I make an array for the fields and use it, as follows: $colsx = array('country,', 'stateProvince,', 'city3,', 'city3Geocode,', 'monthlyRental'); $query = "INSERT INTO `$table` ('$colsx') VALUES ( '$country', '$stateProvince', '$city3', '$city3Geocode', '$monthlyRental')"; I get a MySQL error - check the manual that corresponds to your MySQL server version for the right syntax to use near ''Array') VALUES ( 'US', 'New York', 'Fairport, Monroe County, New York', '(43.09)' at line 1. I get this error whether the array items have commas inside the single quotes or not. I've done a lot of reading and tried many combinations and I can't get it. I want to see the proper syntax on a small scale before I go back to foreach expressions to process $_POST and both the fields and values are arrays. And yes, I know I should use mysql_real_escape_string, but that is an easy later step in the foreach. Lastly, some clues about the syntax for an array of values would be helpful, particularly if it is different from the fields array. I know I need to add a null as the first array item to trigger the MySQL autoincrement id. What else? I'm pretty new, so please be specific.

    Read the article

  • Android: database reading problem throws exception

    - by Vamsi
    Hi, i am having this problem with the android database. I adopted the DBAdapter file the NotepadAdv3 example from the google android page. DBAdapter.java public class DBAdapter { private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "PasswordDb"; private static final String DATABASE_TABLE = "myuserdata"; private static final String DATABASE_USERKEY = "myuserkey"; private static final int DATABASE_VERSION = 2; public static final String KEY_USERKEY = "userkey"; public static final String KEY_TITLE = "title"; public static final String KEY_DATA = "data"; public static final String KEY_ROWID = "_id"; private final Context mContext; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; private static final String DB_CREATE_KEY = "create table " + DATABASE_USERKEY + " (" + "userkey text not null" +");"; private static final String DB_CREATE_DATA = "create table " + DATABASE_TABLE + " (" + "_id integer primary key autoincrement, " + "title text not null" + "data text" +");"; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DB_CREATE_KEY); db.execSQL(DB_CREATE_DATA); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS myuserkey"); db.execSQL("DROP TABLE IF EXISTS myuserdata"); onCreate(db); } } public DBAdapter(Context ctx) { this.mContext = ctx; } public DBAdapter Open() throws SQLException{ try { mDbHelper = new DatabaseHelper(mContext); } catch(Exception e){ Log.e(TAG, e.toString()); } mDb = mDbHelper.getWritableDatabase(); return this; } public void close(){ mDbHelper.close(); } public Long storeKey(String userKey){ ContentValues initialValues = new ContentValues(); initialValues.put(KEY_USERKEY, userKey); try { mDb.delete(DATABASE_USERKEY, "1=1", null); } catch(Exception e) { Log.e(TAG, e.toString()); } return mDb.insert(DATABASE_USERKEY, null, initialValues); } public String retrieveKey() { final Cursor c; try { c = mDb.query(DATABASE_USERKEY, new String[] { KEY_USERKEY}, null, null, null, null, null); }catch(Exception e){ Log.e(TAG, e.toString()); return ""; } if(c.moveToFirst()){ return c.getString(0); } else{ Log.d(TAG, "UserKey Empty"); } return ""; } //not including any function related to "myuserdata" table } Class1.java { mUserKey = mDbHelper.retrieveKey(); mDbHelper.storeKey(Key); } the error that i am receiving is from Log.e(TAG, e.toString()) in the methods retrieveKey() and storeKey() "no such table: myuserkey: , while compiling: SELECT userkey FROM myuserkey"

    Read the article

  • Help with ListView Databse

    - by Weston Dunn
    I am having issues @ run with this code: App Force Closing.. Sprinter.Java import android.app.ListActivity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.widget.ListAdapter; import android.widget.SimpleCursorAdapter; public class Sprinter extends ListActivity { /** Called when the activity is first created. */ final static String MY_DB_NAME = "Sprinter"; final static String MY_DB_TABLE = "Stations"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SQLiteDatabase myDB = null; try { myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null); myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE + "_id integer primary key autoincrement, name varchar(100);"); myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (_id, name)" + " VALUES ('', 'Oceanside Transit Center');"); myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (_id, name)" + " VALUES ('', 'Coast Highway');"); Cursor mCursor = myDB.rawQuery("SELECT name" + " FROM " + MY_DB_TABLE, null); startManagingCursor(mCursor); ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_item, mCursor, new String[] { "name" }, new int[] { R.id.Name }); this.setListAdapter(adapter); this.getListView().setTextFilterEnabled(true); } finally { if (myDB != null) { myDB.close(); } } } } main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ListView android:id="@id/android:list" android:layout_width="wrap_content" android:layout_height="wrap_content"> </ListView> <TextView android:id="@id/android:empty" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="No Data" /> </LinearLayout> list_item.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/LinearLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <TextView android:id="@+id/Name" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> </LinearLayout>

    Read the article

  • Entering and retrieving data from SQLite for an android List View

    - by Infiniti Fizz
    Hi all, I started learning android development a few weeks ago and have gone through the developer.android.com tutorials etc. But now I have a problem. I'm trying to create an app which tracks the usage of each installed app. Therefore I'm pulling the names of all installed apps using the PackageManager and then trying to put them into an SQLite database table. I am using the Notepad Tutorial SQLite implementation but I'm running into some problems that I have tried for days to solve. I have 2 classes, the DBHelper class and the actual ListActivity class. For some reason the app force closes when I try and run my fillDatabase() function which gets all the app names from the PackageManager and tries to put them into the database: private void fillDatabase() { PackageManager manager = this.getPackageManager(); List<ApplicationInfo> appList = manager.getInstalledApplications(0); for(int i = 0; i < appList.size(); i++) { mDbHelper.addApp(manager.getApplicationLabel(appList.get(i)).toString(), 0); } } addApp() is a function defined in my AppsDbHelper class and looks as follows: public long createApp(String name, int usage) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_NAME, name); initialValues.put(KEY_USAGE, usage); return mDb.insert(DATABASE_TABLE, null, initialValues); } The database create is defined as follows: private static final String DATABASE_CREATE = "create table notes (_id integer primary key autoincrement, " + "title text not null, usage integer not null);"; I have commented out all statements that follow fillDatabase(); in the onCreate() method of the ListActivity and so know that it is definetely the problem but I don't know why. I am taking the appName and putting it into the KEY_NAME field of the row and putting 0 into the KEY_USAGE field of the row (because initially, my app will default the usage of each app to 0 (not used yet)). If my addApp() function doesn't take the usage and just puts KEY_NAME into the ContentValues and into the database, it seems to work fine, but I want a column for usage. Any ideas why it is not working? Have I overlooked something? Thanks for your time, InfinitiFizz

    Read the article

  • Need help with joins in sqlalchemy

    - by Steve
    I'm new to Python, as well as SQL Alchemy, but not the underlying development and database concepts. I know what I want to do and how I'd do it manually, but I'm trying to learn how an ORM works. I have two tables, Images and Keywords. The Images table contains an id column that is its primary key, as well as some other metadata. The Keywords table contains only an id column (foreign key to Images) and a keyword column. I'm trying to properly declare this relationship using the declarative syntax, which I think I've done correctly. Base = declarative_base() class Keyword(Base): __tablename__ = 'Keywords' __table_args__ = {'mysql_engine' : 'InnoDB'} id = Column(Integer, ForeignKey('Images.id', ondelete='CASCADE'), primary_key=True) keyword = Column(String(32), primary_key=True) class Image(Base): __tablename__ = 'Images' __table_args__ = {'mysql_engine' : 'InnoDB'} id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(256), nullable=False) keywords = relationship(Keyword, backref='image') This represents a many-to-many relationship. One image can have many keywords, and one keyword can relate back to many images. I want to do a keyword search of my images. I've tried the following with no luck. Conceptually this would've been nice, but I understand why it doesn't work. image = session.query(Image).filter(Image.keywords.contains('boy')) I keep getting errors about no foreign key relationship, which seems clearly defined to me. I saw something about making sure I get the right 'join', and I'm using 'from sqlalchemy.orm import join', but still no luck. image = session.query(Image).select_from(join(Image, Keyword)).\ filter(Keyword.keyword == 'boy') I added the specific join clause to the query to help it along, though as I understand it, I shouldn't have to do this. image = session.query(Image).select_from(join(Image, Keyword, Image.id==Keyword.id)).filter(Keyword.keyword == 'boy') So finally I switched tactics and tried querying the keywords and then using the backreference. However, when I try to use the '.images' iterating over the result, I get an error that the 'image' property doesn't exist, even though I did declare it as a backref. result = session.query(Keyword).filter(Keyword.keyword == 'boy').all() I want to be able to query a unique set of image matches on a set of keywords. I just can't guess my way to the syntax, and I've spent days reading the SQL Alchemy documentation trying to piece this out myself. I would very much appreciate anyone who can point out what I'm missing.

    Read the article

  • Gotchas INSERTing into SQLite on Android?

    - by paul.meier
    Hi friends, I'm trying to set up a simple SQLite database in Android, handling the schema via a subclass of SQLiteOpenHelper. However, when I query my tables, the columns I think I've inserted are never present. Namely, in SQLiteOpenHelper's onCreate(SQLiteDatabase db) method, I use db.execSQL() to run CREATE TABLE commands, then have tried both db.execSQL and db.insert() to run INSERT commands on the tables I've just created. This appears to run fine, but when I try to query them I always get 0 rows returned (for debugging, the queries I'm running are simple SELECT * FROM table and checking the Cursor's getCount()). Anybody run into anything like this before? These commands seem to run on command-line sqlite3. Are they're gotchas that I'm missing (e.g. INSERTS must/must not be semicolon terminated, or some issue involving multiple tables)? I've attached some of the code below. Thanks for your time, and let me know if I can clarify further. @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE "+ LEVEL_TABLE +" (" + " "+ _ID +" INTEGER PRIMARY KEY AUTOINCREMENT," + " level TEXT NOT NULL,"+ " rows INTEGER NOT NULL,"+ " cols INTEGER NOT NULL);"); db.execSQL("CREATE TABLE "+ DYNAMICS_TABLE +" (" + " level_id INTEGER NOT NULL," + " row INTEGER NOT NULL,"+ " col INTEGER NOT NULL,"+ " type INTEGER NOT NULL);"); db.execSQL("CREATE TABLE "+ SCORE_TABLE +" (" + " level_id INTEGER NOT NULL," + " score INTEGER NOT NULL,"+ " date_achieved DATE NOT NULL,"+ " name TEXT NOT NULL);"); this.enterFirstLevel(db); } And a sample of the insert code I'm currently using, which gets called in enterFirstLevel() (some values hard-coded just to get it running...): private void insertDynamic(SQLiteDatabase db, int row, int col, int type) { ContentValues values = new ContentValues(); values.put("level_id", "1"); values.put("row", Integer.toString(row)); values.put("col", Integer.toString(col)); values.put("type", Integer.toString(type)); db.insertOrThrow(DYNAMICS_TABLE, "col", values); } Finally, query code looks like this: private Cursor fetchLevelDynamics(int id) { SQLiteDatabase db = this.leveldata.getReadableDatabase(); try { String fetchQuery = "SELECT * FROM " + DYNAMICS_TABLE; String[] queryArgs = new String[0]; Cursor cursor = db.rawQuery(fetchQuery, queryArgs); Activity activity = (Activity) this.context; activity.startManagingCursor(cursor); return cursor; } finally { db.close(); } }

    Read the article

  • openDatabase Hello World

    - by cf_PhillipSenn
    I'm trying to learn about openDatabase, and I think this I'm getting it to INSERT INTO TABLE1, but I can't verify that the SELECT * FROM TABLE1 is working. <html> <head> <script src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("jquery", "1"); </script> <script type="text/javascript"> var db; $(function(){ db = openDatabase('HelloWorld'); db.transaction( function(transaction) { transaction.executeSql( 'CREATE TABLE IF NOT EXISTS Table1 ' + ' (TableID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ' + ' Field1 TEXT NOT NULL );' ); } ); db.transaction( function(transaction) { transaction.executeSql( 'SELECT * FROM Table1;',function (transaction, result) { for (var i=0; i < result.rows.length; i++) { alert('1'); $('body').append(result.rows.item(i)); } }, errorHandler ); } ); $('form').submit(function() { var xxx = $('#xxx').val(); db.transaction( function(transaction) { transaction.executeSql( 'INSERT INTO Table1 (Field1) VALUES (?);', [xxx], function(){ alert('Saved!'); }, errorHandler ); } ); return false; }); }); function errorHandler(transaction, error) { alert('Oops. Error was '+error.message+' (Code '+error.code+')'); transaction.executeSql('INSERT INTO errors (code, message) VALUES (?, ?);', [error.code, error.message]); return false; } </script> </head> <body> <form method="post"> <input name="xxx" id="xxx" /> <p> <input type="submit" name="OK" /> </p> <a href="http://www.google.com">Cancel</a> </form> </body> </html>

    Read the article

  • How SQLite on Android handles long stings?

    - by Levara
    Hi! I'm wondering how Android's implementation of SQLite handles long Strings. Reading from online documentation on sqlite, it said that strings in sqlite are limited to 1 million characters. My strings are definitely smaller. I'm creating a simple RSS application, and after parsing a html document, and extracting text, I'm having problem saving it to a database. I have 2 tables in database, feeds and articles. RSS feeds are correctly saved and retrieved from feeds table, but when saving to the articles table, logcat is saying that it cannot save extracted text to it's column. I don't know if other columns are making problems too, no mention of them in logcat. I'm wondering, since text is from an article on web, are signs like (",',;) creating problems? Is Android automaticaly escaping them, or I have to do that. I'm using a technique for inserting similar to one in notepad tutorial: public long insertArticle(long feedid, String title, String link, String description, String h1, String h2, String h3, String p, String image, long date) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_FEEDID, feedid); initialValues.put(KEY_TITLE, title); initialValues.put(KEY_LINK, link); initialValues.put(KEY_DESCRIPTION, description ); initialValues.put(KEY_H1, h1 ); initialValues.put(KEY_H2, h2); initialValues.put(KEY_H3, h3); initialValues.put(KEY_P, p); initialValues.put(KEY_IMAGE, image); initialValues.put(KEY_DATE, date); return mDb.insert(DATABASE_TABLE_ARTICLES,null, initialValues); } Column P is for extracted text, h1, h2 and h3 are for headers from a page. Logcat reports only column p to be the problem. The table is created with following statement: private static final String DATABASE_CREATE_ARTICLES = "create table articles( _id integer primary key autoincrement, feedid integer, title text, link text not null, description text," + "h1 text, h2 text, h3 text, p text, image text, date integer);"; Thanks!

    Read the article

  • Adding Information in SQLite

    - by Cam
    Hi All, I am having trouble with my Android App when adding information into SQLite. I am relatively new to Java/SQLite and though I have followed a lot of tutorials on SQLite and have been able to get the example code to run I am unable to get tables to be created and data to import when running my own app. I have included my code in two Java files Questions (Main Program) and QuestionData (helper class represents the database). Questions.java: public class Questions extends Activity { private QuestionData questions; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.quiztest); questions = new QuestionData(this); try { Cursor cursor = getQuestions(); showQuestions(cursor); } finally { questions.close(); } } private Cursor getQuestions() { //Select Query String loadQuestions = "SELECT * FROM questionlist"; SQLiteDatabase db = questions.getReadableDatabase(); Cursor cursor = db.rawQuery(loadQuestions, null); startManagingCursor(cursor); return cursor; } private void showQuestions(Cursor cursor) { // Collect String Values from Query and Display them this part of the code is wokring fine when there is data present. QuestionData.java public class QuestionData extends SQLiteOpenHelper { private static final String DATABASE_NAME = "TriviaQuiz.db" ; private static final int DATABASE_VERSION = 2; public QuestionData(Context ctx) { super(ctx, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE questionlist (_id INTEGER PRIMARY KEY AUTOINCREMENT, QID TEXT, QQuestion TEXT, QAnswer TEXT, QOption1 TEXT, QOption2 TEXT, QOption3 TEXT, QCategoryTagLvl1 TEXT, QCategoryTagLvl2 TEXT, QOptionalTag1 TEXT, QOptionalTag2 TEXT, QOptionalTag3 TEXT, QOptionalTag4 TEXT, QOptionalTag5 TEXT, QTimePeriod TEXT, QDifficultyRating TEXT, QGenderBias TEXT, QAgeBias TEXT, QRegion TEXT, QWikiLink TEXT, QValidationLink1 TEXT, QValidationLink2 TEXT, QHint TEXT, QLastValidation TEXT, QNotes TEXT, QMultimediaType TEXT, QMultimediaLink TEXT, QLastAsked TEXT);"); db.execSQL("INSERT INTO questionlist (_id, QID, QQuestion, QAnswer, QOption1, QOption2, QOption3, QCategoryTagLvl1, QCategoryTagLvl2, QOptionalTag1, QOptionalTag2, QOptionalTag3, QOptionalTag4, QOptionalTag5, QTimePeriod, QDifficultyRating, QGenderBias, QAgeBias, QRegion, QWikiLink, QValidationLink1, QValidationLink2, QHint, QLastValidation, QNotes, QMultimediaType, QMultimediaLink, QLastAsked)"+ "VALUES (null,'Q00001','Example','Ans1','Q1','Q2','Q3','Q4','','','','','','','','','','','','','','','','','','','','')"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } } Any suggestions at all would be great. I have tried debugging which suggests that the database does not exist. Thanks in advance for your assistance.

    Read the article

  • Propel Single Table Inheritance Issue

    - by lo_fye
    I have a table called "talk", which is defined as abstract in my schema.xml file. It generates 4 objects (1 per classkey): Comment, Rating, Review, Checkin It also generates TalkPeer, but I couldn't get it to generate the other 4 peers (CommentPeer, RatingPeer, ReviewPeer, CheckinPeer), so I created them by hand, and made them inherit from TalkPeer.php, which inherits from BaseTalkPeer. I then implemented getOMClass() in each of those peers. The problem is that when I do queries using the 4 peers, they return all 4 types of objects. That is, ReviewPeer will return Visits, Ratings, Comments, AND Reviews. Example: $c = new Criteria(); $c->add(RatingPeer::VALUE, 5, Criteria::GREATER_THAN); $positive_ratings = RatingPeer::doSelect($c); This returns all comments, ratings, reviews, & checkins that have a value 5. ReviewPeer should only return Review objects, and can't figure out how to do this. Do I actually have to go through and change all my criteria to manually specify the classkey? That seems a little pointless, since the Peer name already distinct. I don't want to have to customize each Peer. I should be able to customize JUST the TalkPeer, since they all inherit from it... I just can't figure out how. I tried changing doSelectStmt just in TalkPeer so that it automatically adds the CLASSKEY restriction to the Criteria. It almost works, but I get a: Fatal error: Cannot instantiate abstract class Talk in /models/om/BaseTalkPeer.php on line 503. Line 503 is in BaseTalkPeer::populateObjects(), and is the 3rd line below: $cls = TalkPeer::getOMClass($row, 0); $cls = substr('.'.$cls, strrpos('.'.$cls, '.') + 1); $obj = new $cls(); The docs talked about overriding BaseTalkPeer::populateObject(). I have a feeling that's my problem, but even after reading the source code, I still couldn't figure out how to get it to work. Here is what I tried in TalkPeer::doSelectStmt: public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) { $keys = array('models.Visit'=>1,'models.Comment'=>2,'models.Rating'=>3,'models.Review'=>4); $class_name = self::getOMClass(); if(isset($keys[$class_name])) { //Talk itself is not a returnable type, so we must check $class_key = $keys[$class_name]; $criteria->add(TalkPeer::CLASS_KEY, $class_key); } return parent::doSelectStmt($criteria, $con = null); } Here is an example of my getOMClass method from ReviewPeer: public static function getOMClass() { return self::CLASSNAME_4; //aka 'talk.Review'; } Here is the relevant bit of my schema: <table name="talk" idMethod="native" abstract="true"> <column name="talk_pk" type="INTEGER" required="true" autoIncrement="true" primaryKey="true" /> <column name="class_key" type="INTEGER" required="true" default="" inheritance="single"> <inheritance key="1" class="Visit" extends="models.Talk" /> <inheritance key="2" class="Comment" extends="models.Talk" /> <inheritance key="3" class="Rating" extends="models.Talk" /> <inheritance key="4" class="Review" extends="models.Rating" /> </column> </table> P.S. - No, I can't upgrade from 1.3 to 1.4. There's just too much code that would need to be re-tested

    Read the article

  • Data won't save to SQL database, getting error "close() was never explicitly called on database"

    - by SnowLeppard
    I have a save button in the activity where the user enters data which does this: String subjectName = etName.getText().toString(); String subjectColour = etColour.getText().toString(); SQLDatabase entrySubject = new SQLDatabase(AddSubject.this); entrySubject.open(); entrySubject.createSubjectEntry(subjectName, subjectColour); entrySubject.close(); Which refers to this SQL database class: package com.***.schooltimetable; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class SQLDatabase { public static final String KEY_SUBJECTS_ROWID = "_id"; public static final String KEY_SUBJECTNAME = "name"; public static final String KEY_COLOUR = "colour"; private static final String DATABASE_NAME = "Database"; private static final String DATABASE_TABLE_SUBJECTS = "tSubjects"; private static final int DATABASE_VERSION = 1; private DbHelper ourHelper; private final Context ourContext; private SQLiteDatabase ourDatabase; private static class DbHelper extends SQLiteOpenHelper { public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("CREATE TABLE " + DATABASE_TABLE_SUBJECTS + " (" + KEY_SUBJECTS_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_SUBJECTNAME + " TEXT NOT NULL, " + KEY_COLOUR + " TEXT NOT NULL);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_SUBJECTS); onCreate(db); } } public SQLDatabase(Context c) { ourContext = c; } public SQLDatabase open() throws SQLException { ourHelper = new DbHelper(ourContext); ourDatabase = ourHelper.getWritableDatabase(); return this; } public void close() { ourHelper.close(); } public long createSubjectEntry(String subjectName, String subjectColour) { // TODO Auto-generated method stub ContentValues cv = new ContentValues(); cv.put(KEY_SUBJECTNAME, subjectName); cv.put(KEY_COLOUR, subjectColour); return ourDatabase.insert(DATABASE_TABLE_SUBJECTS, null, cv); } public String[][] getSubjects() { // TODO Auto-generated method stub String[] Columns = new String[] { KEY_SUBJECTNAME, KEY_COLOUR }; Cursor c = ourDatabase.query(DATABASE_TABLE_SUBJECTS, Columns, null, null, null, null, null); String[][] Result = new String[1][]; // int iRow = c.getColumnIndex(KEY_LESSONS_ROWID); int iName = c.getColumnIndex(KEY_SUBJECTNAME); int iColour = c.getColumnIndex(KEY_COLOUR); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { Result[0][c.getPosition()] = c.getString(iName); Result[1][c.getPosition()] = c.getString(iColour); Settings.subjectCount = c.getPosition(); TimetableEntry.subjectCount = c.getPosition(); } return Result; } This class has other variables and other variations of the same methods for multiple tables in the database, i've cut out the irrelevant ones. I'm not sure what I need to close and where, I've got the entrySubject.close() in my activity. I used the methods for the database from the NewBoston tutorials. Can anyone see what I've done wrong, or where my problem is? Thanks.

    Read the article

  • syntax error in sql query?

    - by user1550588
    I want to create some tables in database so for that i wright some queries to create table. but i got an error "there was a syntax error in your sql statement". I check all my queries but i am not able to find what syntax i wright wrong. here i attached my sql queries please told me what is wrong with queries. Thanks in advance. CREATE TABLE "WATER&SEWAGE" { "CUSTOMER_ID" VARCHAR, "POTABLE_WATER" VARCHAR, "HOT_WATER" VARCHAR, "SAFETY" VARCHAR, "T/P_VALVE+EXT" VARCHAR, "HEATER_TYPE" VARCHAR, "GAS_VENT_CONDITION" VARCHAR, "FIRE_BOX_CONDITION" VARCHAR, "PRESSURE" VARCHAR, "BACK_FLOW" VARCHAR, "PLUMBING_CONDITION" VARCHAR, "CABINET_CONDITION" VARCHAR, "3_COMP_SINK" VARCHAR, "WATER_HEATER" VARCHAR, "CLEAN_OUT_CONDITION" VARCHAR, "FLOOR_DRAIN" VARCHAR, "FLOOR_SINK" VARCHAR, "MAINTANANCE" VARCHAR, "COMMENTS" VARCHAR, "EVIDENCE_PHOTOS" VARCHAR) CREATE TABLE "TIME_AND_TETMPERATURE_REL" ("CUSTOMER_ID" INTEGER, "THERMOMTE_AVAILABLE" VARCHAR, "THERMO_TYPE" VARCHAR, "COLD_TEMP" VARCHAR, "FOOD_TYPE1" VARCHAR, "PROPER_COOLING" VARCHAR, "FOOD_TYPE2" VARCHAR, "COMPLIANCE" VARCHAR, "FOOD_TYPE3" VARCHAR, "TPHC" VARCHAR, "HACCP" VARCHAR, "HOT_HOLDING_TEMP" VARCHAR, "FOOD_TYPE4" VARCHAR, "HOT_TEMP" VARCHAR, "FOOD_TYPE5" VARCHAR, "IMPROPER_REHEATING" VARCHAR, "FOOD_TYPE6" VARCHAR, "FOOD_OUT_OF_TEMP" VARCHAR, "WRITTEN_PLAN_FILES" VARCHAR, "EMPLOYEE_KNOWLEDGE" VARCHAR, "TIME_KEEPING_METHODS" VARCHAR, "HACCP_METHODS" VARCHAR, "CALIBRATION" VARCHAR, "COOKING_TEMP" VARCHAR, "EQUIP_CONDITION" VARCHAR, "COMMENTS" VARCHAR, "EVIDENCE_PHOTOS" VARCHAR) CREATE TABLE "PROTECTION_FROM_CONTAMINATION" ("FOOD_ADULTERATION" VARCHAR, "FOOD_SPOILAGE" VARCHAR, "CONTAMINATION" VARCHAR, "FOOD_STORAGE" VARCHAR, "REFRIGRATORS" VARCHAR, "FREEZER" VARCHAR, "FIFO" VARCHAR, "DRY" VARCHAR, "DISHWASHING_CHEMICALS" VARCHAR, "CLEANING" VARCHAR, "SANITIZER" VARCHAR, "SUPPLY_EQUIPMENT" VARCHAR, "PESTICIDES" VARCHAR, "COMMENTS" VARCHAR, "EVIDENCE_PHOTOS" VARCHAR, "CUSTOMER_ID" INTEGER) CREATE TABLE "PHYSICAL_FACILITIES_2" ("CUSTOMER_ID" VARCHAR, "CEILING" VARCHAR, "WINDOWS" VARCHAR, "SPOILS_STORAGE" VARCHAR, "DOORS" VARCHAR, "PERSONAL_LOCKERS" VARCHAR, "FLOORS" VARCHAR, "CONDITION" VARCHAR, "HANDICAP" VARCHAR, "SELF_CLOSING_ROOM" VARCHAR, "TOILETS" VARCHAR, "TOILET_PAPER" VARCHAR, "TOILET_CONDITION" VARCHAR, "VENTILATION_CONDITION" VARCHAR, "MENS" VARCHAR, "MEN'S_VENTILATION" VARCHAR, "MEN'S_FLOOR_DRAWN" VARCHAR, "MEN'S_TOILET_STALLS" VARCHAR, "MEN'S_HAND_SINK" VARCHAR, "MEN'S_TOWELS" VARCHAR, "WOMEN'S" VARCHAR, "WOMEN'S_VENTILATION" VARCHAR, "WOMEN'S_FLOOR_DRAWN" VARCHAR, "WOMEN'S_TOILET_STALLS" VARCHAR, "WOMEN'S_HAND_SINK" VARCHAR, "WOMEN'S_TOWELS" VARCHAR, "COMMENTS" VARCHAR, "EVIDENCE_PHOTOS" VARCHAR) CREATE TABLE "PHYSICAL_FACILITIES_1" ("CUSTOMER_ID" VARCHAR, "LIGHTNING" VARCHAR, "KITCHEN" VARCHAR, "STORAGE" VARCHAR, "REFRIGRATION" VARCHAR, "JANITORIAL" VARCHAR, "INTERIOR" VARCHAR, "FIXTURE" VARCHAR, "FOOTCANDLES_1" VARCHAR, "FOOTCANDLES_2" VARCHAR, "FOOTCANDLES_3" VARCHAR, "FOOTCANDLES_4" VARCHAR, "FOOTCANDLES_5" VARCHAR, "EXTERIOR" VARCHAR, "WINDOWS" VARCHAR, "GLASS" VARCHAR, "SCREEN" VARCHAR, "COMMENTS" VARCHAR, "EVIDENCE_PHOTOS" VARCHAR) CREATE TABLE "PEST_CONTROL" ("CUSTOMER_ID" VARCHAR, "WALL/CEILING_PIPES" VARCHAR, "SANITATION" VARCHAR, "DOORS" VARCHAR, "SELF_CLOSING" VARCHAR, "RODENT_PROOF" VARCHAR, "VERMIN_PROOFING" VARCHAR, "FOUNDATION" VARCHAR, "ATTIC_VENTS" VARCHAR, "WINDOWS" VARCHAR, "TYPE_SCREENS" VARCHAR, "COMMENTS" VARCHAR, "EVIDENCE_PHOTOS" VARCHAR) CREATE TABLE "GENERAL_FOOD_SAFETY_REQ" ("CUSTOMER_ID" VARCHAR, "APPROVED_METHODS" VARCHAR, "DEFROST" VARCHAR, "FROZEN_FOOD" VARCHAR, "FOOD_WASHING" VARCHAR, "PRODUCE_1" VARCHAR, "FRUITS" VARCHAR, "GRAINS" VARCHAR, "VEGETABLES" VARCHAR, "SEPERATE_FROM_CONT" VARCHAR, "RAW" VARCHAR, "PRODUCE_2" VARCHAR, "STORED_BULK" VARCHAR, "STORAGE" VARCHAR, "FIFO" VARCHAR, "REFRIGRATAION" VARCHAR, "STORAGE_TEMP" VARCHAR, "HUMIDITY" VARCHAR, "COMMENTS" VARCHAR, "EVIDENCE_PHOTOS" VARCHAR) CREATE TABLE "FOOD_SAFETY_CERTIFICATION" ("CUSTOMER_ID" INTEGER,"OWNER" VARCHAR,"MANAGER" VARCHAR,"EMPLOYEE" VARCHAR,"NAME1" VARCHAR,"NAT'L_REGISTRY1" VARCHAR,"PROMETRIC1" VARCHAR,"SERVESAFE1" VARCHAR,"EXPIRATION1" VARCHAR,"NAME2" VARCHAR,"NAT'L_REGISTRY2" VARCHAR,"PROMETRIC2" VARCHAR,"SERVESAFE2" VARCHAR,"EXPIRATION2" VARCHAR,"COMMENTS" VARCHAR,"FOOD_TEMP" VARCHAR,"DISHWASHER" VARCHAR,"DANGER_ZONE" VARCHAR,"COOLING_FOODS" VARCHAR,"THAWING" VARCHAR,"REHEATING" VARCHAR,"THERMOMETERS" VARCHAR,"FIFO" VARCHAR,"HANDWASH" VARCHAR,"COOKING_TEMP" VARCHAR,"FOOD_POISONING_TYPES" VARCHAR,"EVEDENCE_PHOTOS" VARCHAR) CREATE TABLE "FOOD_FROM_APPROVED_SOURCES" ("CUSTOMER_ID" VARCHAR, "RECEIPTS" VARCHAR, "DELIVERY_DOOR" VARCHAR, "AIR_CURTAIN" VARCHAR, "VELOCITY" VARCHAR, "OFF_LOAD" VARCHAR, "INSPECTS" VARCHAR, "RODENTS" VARCHAR, "WARNING" VARCHAR, "SHELL_FISH" VARCHAR, "GULF_OYSTER" VARCHAR, "FOOD_OUT_OF_TEMP" VARCHAR, "COMMENTS" VARCHAR, "EVIDENCE_PHOTO" VARCHAR) CREATE TABLE "FOOD_FACILITY_SITE_FACTS" ("CUSTOMER_ID" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,"DBA" VARCHAR,"DISTRICT" VARCHAR,"CITY" VARCHAR,"ZIPCODE" VARCHAR,"ADDRESS" VARCHAR,"SEAT_NO" VARCHAR,"PHONE_NO" VARCHAR,"OWNER" VARCHAR,"PERSON_IN_CHARGE" VARCHAR,"WEBSITE" VARCHAR,"EMAIL" VARCHAR,"FACILITY_TYPE" VARCHAR,"SQ_FOOTAGE" VARCHAR,"NO_OF_SEATS" VARCHAR,"ALCOHOL_SALES" VARCHAR,"LTD_PREP" VARCHAR,"BUSINESS_LICENCE_NO" VARCHAR,"EXPIRATION" VARCHAR,"COMMENTS" VARCHAR,"EVIDENCE_PHOTOS" VARCHAR) CREATE TABLE "FOOD_DISPLAY_SELF_SERVICE" ("CUSTOMER_ID" VARCHAR, "SELF_SERVICE" VARCHAR, "LIDS" VARCHAR, "UTENSILS" VARCHAR, "HOW_OFTEN_CHANGED" VARCHAR, "SCOOP" VARCHAR, "SNEEZ_GUARD" VARCHAR, "DISHES" VARCHAR, "CROSS" VARCHAR, "SENITATION" VARCHAR, "MAINTANANCE" VARCHAR, "MECHANICAL_CONDITION" VARCHAR, "SERVICE_OF_UTENSIL" VARCHAR, "TIME" VARCHAR, "PRPER_FOOD_LABELING" VARCHAR, "COMMENTS" VARCHAR, "EVIDENCE_PHOTOS" VARCHAR) CREATE TABLE "EQUIPMENT/UTENSILS/LINES" ("CUSTOMER_ID" VARCHAR, "STORED_DISHES" VARCHAR, "CUPS" VARCHAR, "DAMAGED_DISHES" VARCHAR, "UTENSILS" VARCHAR, "LINES" VARCHAR, "COOLING_EQUIPMENT" VARCHAR, "COOK_WARE_STORAGE" VARCHAR, "CONDITION" VARCHAR, "STORAGE_LOCATION" VARCHAR, "NAPKINS" VARCHAR, "SANITATION" VARCHAR, "ADEQUATE_CAPACITY" VARCHAR, "HAZARDS" VARCHAR, "COMMENTS" VARCHAR, "EVIDENCE_PHOTOS" VARCHAR) CREATE TABLE "EMPLOYEE_HEALTH_AND_HYGENE" ("CSTOMER_ID" INTEGER, "COMUNICABLE_DIESEASE" VARCHAR, "WIPING_BAGS" VARCHAR, "DISCHARGE" VARCHAR, "LOCKERS" VARCHAR, "PROPER_HAND_WASH" VARCHAR, "RESTROOM_CONDITION" VARCHAR, "HANDWASH_STATION" VARCHAR, "HAIR_RESTRAINT" VARCHAR, "GLOVES_USED" VARCHAR, "WOUND_CARE" VARCHAR, "FOOD_SAMPLE_TESTING" VARCHAR, "GARMENT_CONDITION" VARCHAR, "HEALTH" VARCHAR, "COMMENTS" VARCHAR, "EVIDENCE_PHOTOS" VARCHAR) CREATE TABLE "DISH&WARE_WASHING" ("CUSTOMER_ID" INTEGER, "TYPE_OF_COMPARTMENT_SINK" VARCHAR, "PLUMBING_ISSUE1" VARCHAR, "QUATERNARY_AMMONIA" VARCHAR, "IODINE" VARCHAR, "HOT_WTR_SANIT_TEMP" VARCHAR, "PLUMBING_ISSUE2" VARCHAR, "HOT_WATER" VARCHAR, "TEMP" VARCHAR, "DISHWASHER_TYPE" VARCHAR, "WAQLL_CONDITION" VARCHAR, "SANITIZER_LEVELS" VARCHAR, "CHLORINE" VARCHAR, "SINK_OR_DISHWASHER" VARCHAR, "EVIDENCE_PHOTOS" VARCHAR) CREATE TABLE "CORRECTIVE_ACTIONS" ("CUSTOMER_ID" VARCHAR, "CORRECTIVE_ACTIONS" VARCHAR) CREATE TABLE "CONSUMER_ADVISORY" ("CUSTOMER_ID" VARCHAR, "TRUTH_IN_MENU" VARCHAR, "MAJOR_CHAIN" VARCHAR, "TRANS_FAT" VARCHAR, "SCHOOL" VARCHAR, "PROHIBITED" VARCHAR, "CALORIES" VARCHAR, "COMMENTS" VARCHAR, "EVEDINCE_PHOTOS" VARCHAR) CREATE TABLE "COMPLAINS&ENFORCEMENTS" ("CUSTOMER_ID" VARCHAR, "PLAN_SUBMITTED" VARCHAR, "APPROVEL" VARCHAR, "CERTIFICATE_OF_OCCU" VARCHAR, "PRIOR_INSPEK_REPORT" VARCHAR, "LAST_INSPECTION_DATE" VARCHAR, "PERMIT_STATUS" VARCHAR, "POSTED" VARCHAR, "EXPIRATION" VARCHAR, "PERMIT_DISPLAYED" VARCHAR, "INSPECTION_REPORT_POSTING" VARCHAR, "COMMENTS" VARCHAR, "EVIDENCE_PHOTOS" VARCHAR)

    Read the article

  • Android SQLlite crashes after trying retrieving data from it

    - by Pavel
    Hey everyone. I'm kinda new to android programming so please bear with me. I'm having some problems with retrieving records from the db. Basically, all I want to do is to store latitudes and longitudes which GPS positioning functions outputs and display them in a list using ListActivity on different tab later on. This is how the code for my DBAdapter helper class looks like: public class DBAdapter { public static final String KEY_ROWID = "_id"; public static final String KEY_LATITUDE = "latitude"; public static final String KEY_LONGITUDE = "longitude"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "coords"; private static final String DATABASE_TABLE = "coordsStorage"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_CREATE = "create table coordsStorage (_id integer primary key autoincrement, " + "latitude integer not null, longitude integer not null);"; private final Context context; private DatabaseHelper DBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS titles"); onCreate(db); } } //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a title into the database--- public long insertCoords(int latitude, int longitude) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_LATITUDE, latitude); initialValues.put(KEY_LONGITUDE, longitude); return db.insert(DATABASE_TABLE, null, initialValues); } //---deletes a particular title--- public boolean deleteTitle(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) 0; } //---retrieves all the titles--- public Cursor getAllTitles() { return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_LATITUDE, KEY_LONGITUDE}, null, null, null, null, null); } //---retrieves a particular title--- public Cursor getTitle(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_LATITUDE, KEY_LONGITUDE}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a title--- /*public boolean updateTitle(long rowId, int latitude, int longitude) { ContentValues args = new ContentValues(); args.put(KEY_LATITUDE, latitude); args.put(KEY_LONGITUDE, longitude); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) 0; }*/ } Now my question is - am I doing something wrong here? If yes could someone please tell me what? And how I should retrieve the records in organised list manner? Help would be greatly appreciated!!

    Read the article

  • Android sqlight problem always null

    - by yoav.str
    every time i am using the db its null and i just dont get it i use this code for the SQL when I have quarry : public class GameSQLHelper { static final String[] COUNTRIES = new String[] { "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra" }; private static final String DB_PATH = "/countryCityGame/databases/"; private static final String DATABASE_NAME = "events.db"; private static final int DATABASE_VERSION = 1; private final Context mCtx; // Table name public static final String TABLE = "myDataBase"; // Columns public static final String LETTER = "letter"; public static final String TYPE = "type"; public static final String VALUE = "value"; //my database SQLiteDatabase myDataBase; private static class DatabaseHelper extends SQLiteOpenHelper { private static final String TAG = null; DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String sql = "create table " + TABLE + "( " + BaseColumns._ID + " integer primary key autoincrement, " + LETTER + " text not null, " + TYPE + " text not null," + VALUE + " text not null );"; Log.d("EventsData", "onCreate: " + sql); db.execSQL(sql); insertValuesToDB(db); } private void insertValuesToDB(SQLiteDatabase db) { if (db == null){ } else{ db.execSQL("INSERT INTO " + TABLE + " ("+LETTER+","+ TYPE +"," + VALUE +")" + " VALUES ('A', 'country', 'Angola');"); ContentValues initialValues = new ContentValues(); for (int i = 0 ; i < COUNTRIES.length ; i++){ Character tmp = (Character)COUNTRIES[i].charAt(0); initialValues.put(VALUE, COUNTRIES[i]); initialValues.put(TYPE, "country"); initialValues.put(LETTER,tmp.toString(tmp)); db.insert(TABLE, null, initialValues); } } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS notes"); onCreate(db); } } /** * Constructor - takes the context to allow the database to be * opened/created * * @param ctx the Context within which to work */ public GameSQLHelper(Context ctx) { this.mCtx = ctx; } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion >= newVersion) return; String sql = null; if (oldVersion == 1) sql = "alter table " + TABLE + " add note text;"; if (oldVersion == 2) sql = ""; Log.d("EventsData", "onUpgrade : " + sql); if (sql != null) db.execSQL(sql); } public void openDataBase() throws SQLException{ //Open the database String myPath = DB_PATH + DATABASE_NAME; myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); } public boolean existInDataBase(String serchStr ){ Cursor c = null ; try{ openDataBase(); c = myDataBase.query(true, TABLE, new String[] {TYPE }, VALUE + "=" + serchStr, null, null, null, null, null); } catch(Exception e){ Log.d("sqlExacption", e.getMessage()); } if (c == null) return false; return true; } } whenever i call this class (i hold an instace of him initialized : mDbHelper = new GameSQLHelper(this); where this is an activity ) i always get my mDbHelper as null how can i change it , its my first time working with sql outside of mysql platform so i am kind of having problmes understanding tje concept , and the android notepad example didnt help me .

    Read the article

  • openDatabase Hello World - 2

    - by cf_PhillipSenn
    This is a continuation from a previous stackoverflow question. I've renamed some variables so that I can tell what are keywords and what are names that I can control. Q: Why is the deleteRow function not working? <html> <head> <title>html5 openDatabase Hello World</title> <script src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("jquery", "1"); google.setOnLoadCallback(OnLoadCallback); function OnLoadCallback() { var dbo; dbo = openDatabase('HelloWorld'); dbo.transaction( function(T1) { T1.executeSql( 'CREATE TABLE IF NOT EXISTS myTable ' + ' (myTableID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ' + ' Field1 TEXT NOT NULL );' ); } ); dbo.transaction(function(T2) { T2.executeSql('SELECT * FROM myTable',[], function (T6, result) { for (var i=0; i < result.rows.length; i++) { var row = result.rows.item(i); $('#savedData').append('<li id="'+row.myTableID+'">' + row.Field1 + '</li>'); } }, errorHandler); }); $('form').submit(function() { var xxx = $('#xxx').val(); dbo.transaction( function(T3) { T3.executeSql( 'INSERT INTO myTable (Field1) VALUES (?);', [xxx], function(){ $('#savedData').append('<li id="ThisisWhereIneedHELP">' + xxx + '</li>'); $('#xxx').val(''); }, errorHandler ); } ); return false; }); $('#savedData > li').live('click', function (){ deleteRow(this.id); $(this).remove(); }); } function deleteRow(myTableID) { alert('trying to delete'); dbo.transaction(function(T4) { T4.executeSql('DELETE FROM myTable WHERE myTableID = ?', [myTableID], function(){ alert('Deleted!'); }, errorHandler); }); } function errorHandler(T5, error) { alert('Oops. Error was '+error.message+' (Code '+error.code+')'); // T5.executeSql('INSERT INTO errors (code, message) VALUES (?, ?);', // [error.code, error.message]); return false; } </script> </head> <body> <form method="post"> <input name="xxx" id="xxx" /> <p> <input type="submit" name="OK" /> </p> <ul id="savedData"> </ul> </form> </body> </html>

    Read the article

< Previous Page | 3 4 5 6 7 8  | Next Page >