Search Results

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

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

  • How to read large number of rows efficiently using Zend_Db?

    - by Alex N.
    Is there a simple :) and efficient way or reading very large number of rows sequentially using Zend_Db? Basically I need to process entire table, row by row. Table is large, primary key sequence is not guaranteed(i.e. not an autoincrement, but is UNSIGNED INT). What's the best way to approach this? Environment: PHP 5.2, Zend Framework 1.10, MySQL 5.1

    Read the article

  • Metro: Creating an IndexedDbDataSource for WinJS

    - by Stephen.Walther
    The goal of this blog entry is to describe how you can create custom data sources which you can use with the controls in the WinJS library. In particular, I explain how you can create an IndexedDbDataSource which you can use to store and retrieve data from an IndexedDB database. If you want to skip ahead, and ignore all of the fascinating content in-between, I’ve included the complete code for the IndexedDbDataSource at the very bottom of this blog entry. What is IndexedDB? IndexedDB is a database in the browser. You can use the IndexedDB API with all modern browsers including Firefox, Chrome, and Internet Explorer 10. And, of course, you can use IndexedDB with Metro style apps written with JavaScript. If you need to persist data in a Metro style app written with JavaScript then IndexedDB is a good option. Each Metro app can only interact with its own IndexedDB databases. And, IndexedDB provides you with transactions, indices, and cursors – the elements of any modern database. An IndexedDB database might be different than the type of database that you normally use. An IndexedDB database is an object-oriented database and not a relational database. Instead of storing data in tables, you store data in object stores. You store JavaScript objects in an IndexedDB object store. You create new IndexedDB object stores by handling the upgradeneeded event when you attempt to open a connection to an IndexedDB database. For example, here’s how you would both open a connection to an existing database named TasksDB and create the TasksDB database when it does not already exist: var reqOpen = window.indexedDB.open(“TasksDB”, 2); reqOpen.onupgradeneeded = function (evt) { var newDB = evt.target.result; newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement: true }); }; reqOpen.onsuccess = function () { var db = reqOpen.result; // Do something with db }; When you call window.indexedDB.open(), and the database does not already exist, then the upgradeneeded event is raised. In the code above, the upgradeneeded handler creates a new object store named tasks. The new object store has an auto-increment column named id which acts as the primary key column. If the database already exists with the right version, and you call window.indexedDB.open(), then the success event is raised. At that point, you have an open connection to the existing database and you can start doing something with the database. You use asynchronous methods to interact with an IndexedDB database. For example, the following code illustrates how you would add a new object to the tasks object store: var transaction = db.transaction(“tasks”, “readwrite”); var reqAdd = transaction.objectStore(“tasks”).add({ name: “Feed the dog” }); reqAdd.onsuccess = function() { // Tasks added successfully }; The code above creates a new database transaction, adds a new task to the tasks object store, and handles the success event. If the new task gets added successfully then the success event is raised. Creating a WinJS IndexedDbDataSource The most powerful control in the WinJS library is the ListView control. This is the control that you use to display a collection of items. If you want to display data with a ListView control, you need to bind the control to a data source. The WinJS library includes two objects which you can use as a data source: the List object and the StorageDataSource object. The List object enables you to represent a JavaScript array as a data source and the StorageDataSource enables you to represent the file system as a data source. If you want to bind an IndexedDB database to a ListView then you have a choice. You can either dump the items from the IndexedDB database into a List object or you can create a custom data source. I explored the first approach in a previous blog entry. In this blog entry, I explain how you can create a custom IndexedDB data source. Implementing the IListDataSource Interface You create a custom data source by implementing the IListDataSource interface. This interface contains the contract for the methods which the ListView needs to interact with a data source. The easiest way to implement the IListDataSource interface is to derive a new object from the base VirtualizedDataSource object. The VirtualizedDataSource object requires a data adapter which implements the IListDataAdapter interface. Yes, because of the number of objects involved, this is a little confusing. Your code ends up looking something like this: var IndexedDbDataSource = WinJS.Class.derive( WinJS.UI.VirtualizedDataSource, function (dbName, dbVersion, objectStoreName, upgrade, error) { this._adapter = new IndexedDbDataAdapter(dbName, dbVersion, objectStoreName, upgrade, error); this._baseDataSourceConstructor(this._adapter); }, { nuke: function () { this._adapter.nuke(); }, remove: function (key) { this._adapter.removeInternal(key); } } ); The code above is used to create a new class named IndexedDbDataSource which derives from the base VirtualizedDataSource class. In the constructor for the new class, the base class _baseDataSourceConstructor() method is called. A data adapter is passed to the _baseDataSourceConstructor() method. The code above creates a new method exposed by the IndexedDbDataSource named nuke(). The nuke() method deletes all of the objects from an object store. The code above also overrides a method named remove(). Our derived remove() method accepts any type of key and removes the matching item from the object store. Almost all of the work of creating a custom data source goes into building the data adapter class. The data adapter class implements the IListDataAdapter interface which contains the following methods: · change() · getCount() · insertAfter() · insertAtEnd() · insertAtStart() · insertBefore() · itemsFromDescription() · itemsFromEnd() · itemsFromIndex() · itemsFromKey() · itemsFromStart() · itemSignature() · moveAfter() · moveBefore() · moveToEnd() · moveToStart() · remove() · setNotificationHandler() · compareByIdentity Fortunately, you are not required to implement all of these methods. You only need to implement the methods that you actually need. In the case of the IndexedDbDataSource, I implemented the getCount(), itemsFromIndex(), insertAtEnd(), and remove() methods. If you are creating a read-only data source then you really only need to implement the getCount() and itemsFromIndex() methods. Implementing the getCount() Method The getCount() method returns the total number of items from the data source. So, if you are storing 10,000 items in an object store then this method would return the value 10,000. Here’s how I implemented the getCount() method: getCount: function () { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore().then(function (store) { var reqCount = store.count(); reqCount.onerror = that._error; reqCount.onsuccess = function (evt) { complete(evt.target.result); }; }); }); } The first thing that you should notice is that the getCount() method returns a WinJS promise. This is a requirement. The getCount() method is asynchronous which is a good thing because all of the IndexedDB methods (at least the methods implemented in current browsers) are also asynchronous. The code above retrieves an object store and then uses the IndexedDB count() method to get a count of the items in the object store. The value is returned from the promise by calling complete(). Implementing the itemsFromIndex method When a ListView displays its items, it calls the itemsFromIndex() method. By default, it calls this method multiple times to get different ranges of items. Three parameters are passed to the itemsFromIndex() method: the requestIndex, countBefore, and countAfter parameters. The requestIndex indicates the index of the item from the database to show. The countBefore and countAfter parameters represent hints. These are integer values which represent the number of items before and after the requestIndex to retrieve. Again, these are only hints and you can return as many items before and after the request index as you please. Here’s how I implemented the itemsFromIndex method: itemsFromIndex: function (requestIndex, countBefore, countAfter) { var that = this; return new WinJS.Promise(function (complete, error) { that.getCount().then(function (count) { if (requestIndex >= count) { return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist)); } var startIndex = Math.max(0, requestIndex - countBefore); var endIndex = Math.min(count, requestIndex + countAfter + 1); that._getObjectStore().then(function (store) { var index = 0; var items = []; var req = store.openCursor(); req.onerror = that._error; req.onsuccess = function (evt) { var cursor = evt.target.result; if (index < startIndex) { index = startIndex; cursor.advance(startIndex); return; } if (cursor && index < endIndex) { index++; items.push({ key: cursor.value[store.keyPath].toString(), data: cursor.value }); cursor.continue(); return; } results = { items: items, offset: requestIndex - startIndex, totalCount: count }; complete(results); }; }); }); }); } In the code above, a cursor is used to iterate through the objects in an object store. You fetch the next item in the cursor by calling either the cursor.continue() or cursor.advance() method. The continue() method moves forward by one object and the advance() method moves forward a specified number of objects. Each time you call continue() or advance(), the success event is raised again. If the cursor is null then you know that you have reached the end of the cursor and you can return the results. Some things to be careful about here. First, the return value from the itemsFromIndex() method must implement the IFetchResult interface. In particular, you must return an object which has an items, offset, and totalCount property. Second, each item in the items array must implement the IListItem interface. Each item should have a key and a data property. Implementing the insertAtEnd() Method When creating the IndexedDbDataSource, I wanted to go beyond creating a simple read-only data source and support inserting and deleting objects. If you want to support adding new items with your data source then you need to implement the insertAtEnd() method. Here’s how I implemented the insertAtEnd() method for the IndexedDbDataSource: insertAtEnd:function(unused, data) { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore("readwrite").done(function(store) { var reqAdd = store.add(data); reqAdd.onerror = that._error; reqAdd.onsuccess = function (evt) { var reqGet = store.get(evt.target.result); reqGet.onerror = that._error; reqGet.onsuccess = function (evt) { var newItem = { key:evt.target.result[store.keyPath].toString(), data:evt.target.result } complete(newItem); }; }; }); }); } When implementing the insertAtEnd() method, you need to be careful to return an object which implements the IItem interface. In particular, you should return an object that has a key and a data property. The key must be a string and it uniquely represents the new item added to the data source. The value of the data property represents the new item itself. Implementing the remove() Method Finally, you use the remove() method to remove an item from the data source. You call the remove() method with the key of the item which you want to remove. Implementing the remove() method in the case of the IndexedDbDataSource was a little tricky. The problem is that an IndexedDB object store uses an integer key and the VirtualizedDataSource requires a string key. For that reason, I needed to override the remove() method in the derived IndexedDbDataSource class like this: var IndexedDbDataSource = WinJS.Class.derive( WinJS.UI.VirtualizedDataSource, function (dbName, dbVersion, objectStoreName, upgrade, error) { this._adapter = new IndexedDbDataAdapter(dbName, dbVersion, objectStoreName, upgrade, error); this._baseDataSourceConstructor(this._adapter); }, { nuke: function () { this._adapter.nuke(); }, remove: function (key) { this._adapter.removeInternal(key); } } ); When you call remove(), you end up calling a method of the IndexedDbDataAdapter named removeInternal() . Here’s what the removeInternal() method looks like: setNotificationHandler: function (notificationHandler) { this._notificationHandler = notificationHandler; }, removeInternal: function(key) { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore("readwrite").done(function (store) { var reqDelete = store.delete (key); reqDelete.onerror = that._error; reqDelete.onsuccess = function (evt) { that._notificationHandler.removed(key.toString()); complete(); }; }); }); } The removeInternal() method calls the IndexedDB delete() method to delete an item from the object store. If the item is deleted successfully then the _notificationHandler.remove() method is called. Because we are not implementing the standard IListDataAdapter remove() method, we need to notify the data source (and the ListView control bound to the data source) that an item has been removed. The way that you notify the data source is by calling the _notificationHandler.remove() method. Notice that we get the _notificationHandler in the code above by implementing another method in the IListDataAdapter interface: the setNotificationHandler() method. You can raise the following types of notifications using the _notificationHandler: · beginNotifications() · changed() · endNotifications() · inserted() · invalidateAll() · moved() · removed() · reload() These methods are all part of the IListDataNotificationHandler interface in the WinJS library. Implementing the nuke() Method I wanted to implement a method which would remove all of the items from an object store. Therefore, I created a method named nuke() which calls the IndexedDB clear() method: nuke: function () { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore("readwrite").done(function (store) { var reqClear = store.clear(); reqClear.onerror = that._error; reqClear.onsuccess = function (evt) { that._notificationHandler.reload(); complete(); }; }); }); } Notice that the nuke() method calls the _notificationHandler.reload() method to notify the ListView to reload all of the items from its data source. Because we are implementing a custom method here, we need to use the _notificationHandler to send an update. Using the IndexedDbDataSource To illustrate how you can use the IndexedDbDataSource, I created a simple task list app. You can add new tasks, delete existing tasks, and nuke all of the tasks. You delete an item by selecting an item (swipe or right-click) and clicking the Delete button. Here’s the HTML page which contains the ListView, the form for adding new tasks, and the buttons for deleting and nuking tasks: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>DataSources</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" /> <script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script> <script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script> <!-- DataSources references --> <link href="indexedDb.css" rel="stylesheet" /> <script type="text/javascript" src="indexedDbDataSource.js"></script> <script src="indexedDb.js"></script> </head> <body> <div id="tmplTask" data-win-control="WinJS.Binding.Template"> <div class="taskItem"> Id: <span data-win-bind="innerText:id"></span> <br /><br /> Name: <span data-win-bind="innerText:name"></span> </div> </div> <div id="lvTasks" data-win-control="WinJS.UI.ListView" data-win-options="{ itemTemplate: select('#tmplTask'), selectionMode: 'single' }"></div> <form id="frmAdd"> <fieldset> <legend>Add Task</legend> <label>New Task</label> <input id="inputTaskName" required /> <button>Add</button> </fieldset> </form> <button id="btnNuke">Nuke</button> <button id="btnDelete">Delete</button> </body> </html> And here is the JavaScript code for the TaskList app: /// <reference path="//Microsoft.WinJS.1.0.RC/js/base.js" /> /// <reference path="//Microsoft.WinJS.1.0.RC/js/ui.js" /> function init() { WinJS.UI.processAll().done(function () { var lvTasks = document.getElementById("lvTasks").winControl; // Bind the ListView to its data source var tasksDataSource = new DataSources.IndexedDbDataSource("TasksDB", 1, "tasks", upgrade); lvTasks.itemDataSource = tasksDataSource; // Wire-up Add, Delete, Nuke buttons document.getElementById("frmAdd").addEventListener("submit", function (evt) { evt.preventDefault(); tasksDataSource.beginEdits(); tasksDataSource.insertAtEnd(null, { name: document.getElementById("inputTaskName").value }).done(function (newItem) { tasksDataSource.endEdits(); document.getElementById("frmAdd").reset(); lvTasks.ensureVisible(newItem.index); }); }); document.getElementById("btnDelete").addEventListener("click", function () { if (lvTasks.selection.count() == 1) { lvTasks.selection.getItems().done(function (items) { tasksDataSource.remove(items[0].data.id); }); } }); document.getElementById("btnNuke").addEventListener("click", function () { tasksDataSource.nuke(); }); // This method is called to initialize the IndexedDb database function upgrade(evt) { var newDB = evt.target.result; newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement: true }); } }); } document.addEventListener("DOMContentLoaded", init); The IndexedDbDataSource is created and bound to the ListView control with the following two lines of code: var tasksDataSource = new DataSources.IndexedDbDataSource("TasksDB", 1, "tasks", upgrade); lvTasks.itemDataSource = tasksDataSource; The IndexedDbDataSource is created with four parameters: the name of the database to create, the version of the database to create, the name of the object store to create, and a function which contains code to initialize the new database. The upgrade function creates a new object store named tasks with an auto-increment property named id: function upgrade(evt) { var newDB = evt.target.result; newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement: true }); } The Complete Code for the IndexedDbDataSource Here’s the complete code for the IndexedDbDataSource: (function () { /************************************************ * The IndexedDBDataAdapter enables you to work * with a HTML5 IndexedDB database. *************************************************/ var IndexedDbDataAdapter = WinJS.Class.define( function (dbName, dbVersion, objectStoreName, upgrade, error) { this._dbName = dbName; // database name this._dbVersion = dbVersion; // database version this._objectStoreName = objectStoreName; // object store name this._upgrade = upgrade; // database upgrade script this._error = error || function (evt) { console.log(evt.message); }; }, { /******************************************* * IListDataAdapter Interface Methods ********************************************/ getCount: function () { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore().then(function (store) { var reqCount = store.count(); reqCount.onerror = that._error; reqCount.onsuccess = function (evt) { complete(evt.target.result); }; }); }); }, itemsFromIndex: function (requestIndex, countBefore, countAfter) { var that = this; return new WinJS.Promise(function (complete, error) { that.getCount().then(function (count) { if (requestIndex >= count) { return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist)); } var startIndex = Math.max(0, requestIndex - countBefore); var endIndex = Math.min(count, requestIndex + countAfter + 1); that._getObjectStore().then(function (store) { var index = 0; var items = []; var req = store.openCursor(); req.onerror = that._error; req.onsuccess = function (evt) { var cursor = evt.target.result; if (index < startIndex) { index = startIndex; cursor.advance(startIndex); return; } if (cursor && index < endIndex) { index++; items.push({ key: cursor.value[store.keyPath].toString(), data: cursor.value }); cursor.continue(); return; } results = { items: items, offset: requestIndex - startIndex, totalCount: count }; complete(results); }; }); }); }); }, insertAtEnd:function(unused, data) { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore("readwrite").done(function(store) { var reqAdd = store.add(data); reqAdd.onerror = that._error; reqAdd.onsuccess = function (evt) { var reqGet = store.get(evt.target.result); reqGet.onerror = that._error; reqGet.onsuccess = function (evt) { var newItem = { key:evt.target.result[store.keyPath].toString(), data:evt.target.result } complete(newItem); }; }; }); }); }, setNotificationHandler: function (notificationHandler) { this._notificationHandler = notificationHandler; }, /***************************************** * IndexedDbDataSource Method ******************************************/ removeInternal: function(key) { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore("readwrite").done(function (store) { var reqDelete = store.delete (key); reqDelete.onerror = that._error; reqDelete.onsuccess = function (evt) { that._notificationHandler.removed(key.toString()); complete(); }; }); }); }, nuke: function () { var that = this; return new WinJS.Promise(function (complete, error) { that._getObjectStore("readwrite").done(function (store) { var reqClear = store.clear(); reqClear.onerror = that._error; reqClear.onsuccess = function (evt) { that._notificationHandler.reload(); complete(); }; }); }); }, /******************************************* * Private Methods ********************************************/ _ensureDbOpen: function () { var that = this; // Try to get cached Db if (that._cachedDb) { return WinJS.Promise.wrap(that._cachedDb); } // Otherwise, open the database return new WinJS.Promise(function (complete, error, progress) { var reqOpen = window.indexedDB.open(that._dbName, that._dbVersion); reqOpen.onerror = function (evt) { error(); }; reqOpen.onupgradeneeded = function (evt) { that._upgrade(evt); that._notificationHandler.invalidateAll(); }; reqOpen.onsuccess = function () { that._cachedDb = reqOpen.result; complete(that._cachedDb); }; }); }, _getObjectStore: function (type) { type = type || "readonly"; var that = this; return new WinJS.Promise(function (complete, error) { that._ensureDbOpen().then(function (db) { var transaction = db.transaction(that._objectStoreName, type); complete(transaction.objectStore(that._objectStoreName)); }); }); }, _get: function (key) { return new WinJS.Promise(function (complete, error) { that._getObjectStore().done(function (store) { var reqGet = store.get(key); reqGet.onerror = that._error; reqGet.onsuccess = function (item) { complete(item); }; }); }); } } ); var IndexedDbDataSource = WinJS.Class.derive( WinJS.UI.VirtualizedDataSource, function (dbName, dbVersion, objectStoreName, upgrade, error) { this._adapter = new IndexedDbDataAdapter(dbName, dbVersion, objectStoreName, upgrade, error); this._baseDataSourceConstructor(this._adapter); }, { nuke: function () { this._adapter.nuke(); }, remove: function (key) { this._adapter.removeInternal(key); } } ); WinJS.Namespace.define("DataSources", { IndexedDbDataSource: IndexedDbDataSource }); })(); Summary In this blog post, I provided an overview of how you can create a new data source which you can use with the WinJS library. I described how you can create an IndexedDbDataSource which you can use to bind a ListView control to an IndexedDB database. While describing how you can create a custom data source, I explained how you can implement the IListDataAdapter interface. You also learned how to raise notifications — such as a removed or invalidateAll notification — by taking advantage of the methods of the IListDataNotificationHandler interface.

    Read the article

  • I need an approach to the problem of preventing inserting duplicate records into the database

    - by Maurice
    Apologies is this question is asked on the incorrect "stack" A webservice that I call returns a list of data. The data from the webservice is updated periodically, so a call to the webservice done in one hour could return the same data as a call done in an hour. Also, the data is returned based on a start and end date. We have multiple users that can run the webservice search, and duplicate data is most likely to be returned (especially for historical data). However I don't want to insert this duplicate data in the database. I've created a db table in which the data is stored (most important columns are) Id int autoincrement PK Date date not null --The date to which the data set belongs. LastUpdate date not null --The date the data set was last updated. UserName varchar(50) --The name of the user doing the search. I use sql server 2008 express with c# 4.0 and visual studio 2010. Entity Framework is used as the ORM. If stored procedures could be avoided in the proposed solution, then that will be a plus. Another way of looking interpreting what I'm asking a solution for is as follows: I have a million unique records in my table. A user does a new search. The search results from the user contains around 300k of the data that is already in the db. An efficient solution to finding an inserting only the unique records is needed.

    Read the article

  • Am I missing something about these considerations about Leaderboard's database's schema?

    - by misiMe
    I just finished to develop a mobile game, now I want to implement an online leaerboard using mysql. I'm wondering about the database's schema, I thought about some possibilities: (I didn't got in detail with syntax because my question is just about the logic of it) Name: string; Score: integer I thought to ask the name just the first time. If, in the future, you will modify that, it will call just an update to the name associated with your id. Leaderboard(ID, Name, Score) ID: integer autoincrement, PrimaryKey With this kind of idea maybe the db will grow fast because if you choose everytime a different name for the score, it will add a new entry. Leaderboard(PhoneId, Name, Score) Here PhoneId will be the unique identifier of the phone, PrimaryKey. A con of this choice is that if you want to play with your friends' phone, you can't put a different name for the score. Leaderboard(Name, Score) Here Name is PrimaryKey. With that, if you enter a name that already exists, you will be prompted to choose another one. Do you agree with this considerations? What will you do? Am I missing something?

    Read the article

  • Foreign key constraints in Android using SQLite? on Delete cascade.

    - by LordSnoutimus
    I have two tables: tracks and waypoints, a track can have many waypoints, but a waypoint is assigned to only 1 track. In the way points table I have a column called "trackidfk" which inserts the track_ID once a track is made, however I have not setup Foreign Key constraints on this column. When I delete a track I want to delete the assigned waypoints, is this possible?. I read about using Triggers but I don't think they are supported in Android. To create the waypoints table: public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + LONGITUDE + " INTEGER," + LATITUDE + " INTEGER," + TIME + " INTEGER,"+ TRACK_ID_FK + " INTEGER );");

    Read the article

  • mySQL auto increment problem: Duplicate entry '4294967295' for key 1

    - by Josh
    I have a table of emails. The last record in there for an auto increment id is 3780, which is a legit record. Any new record I now insert is being inserted right there. However, in my logs I have the occasional: Query FAIL: INSERT INTO mail.messages (timestamp_queue) VALUES (:time); Array ( [0] => 23000 [1] => 1062 [2] => Duplicate entry '4294967295' for key 1 ) Somehow, the autoincrement jumped up to the INT max of 4294967295 Why on god's green earth would this get jumped up so high? I have no inserts with an id field. The show status for that table, Auto_increment table now reads: 4294967296 How could something like this occur? I realize the id field should perhaps be a big int, but the worry I have is that somehow this thing jumps back up. Josh

    Read the article

  • ADD COLUMN to sqlite db IF NOT EXISTS - flex/air sqlite?

    - by Adam
    I've got a flex/air app I've been working on, it uses a local sqlite database that is created on the initial application start. I've added some features to the application and in the process I had to add a new field to one of the database tables. My questions is how to I go about getting the application to create one new field that is located in a table that already exists? this is a the line that creates the table stmt.text = "CREATE TABLE IF NOT EXISTS tbl_status ("+"status_id INTEGER PRIMARY KEY AUTOINCREMENT,"+" status_status TEXT)"; And now I'd like to add a status_default field. thanks! Thanks - MPelletier I've add the code you provided and it does add the field, but now the next time I restart my app I get an error - 'status_default' already exists'. So how can I go about adding some sort of a IF NOT EXISTS statement to the line you provided?

    Read the article

  • Select TOP 5 * from SomeTable, using Dataview.RowFilter ?

    - by eugeneK
    I need to select 5 most recent rows from cached Dataview object, is there any way to do that? I've tried but Indexer DataColumn is empty. : public static DataView getLatestFourActive() { DataTable productDataTable = getAll().ToTable(); DataColumn ExpressionColumn = new DataColumn("Indexer",typeof(System.Int32)); ExpressionColumn.Unique = true; ExpressionColumn.AutoIncrement = true; ExpressionColumn.AllowDBNull = false; ExpressionColumn.AutoIncrementSeed = 0; ExpressionColumn.AutoIncrementStep = 1; productDataTable.Columns.Add(ExpressionColumn); DataView productFilteredView = productDataTable.DefaultView; productFilteredView.RowFilter = "isActive=1 and Indexer<4"; return productFilteredView; } getAll() returns cached DataView thanks

    Read the article

  • Doctrine Problem: Couldn't get last insert identifier.

    - by cnkt
    When i try to save data to my model Doctrine throws this exception: Message: Couldn't get last insert identifier. My table setup code is: $this->hasColumn('id', 'integer', 4, array( 'type' => 'integer', 'length' => 4, 'fixed' => false, 'unsigned' => false, 'primary' => true, 'autoincrement' => true, )); Please help. Thanks.

    Read the article

  • Google Gears - Database - VACUUM

    - by Sirber
    With this code: var db = google.gears.factory.create('beta.database'); db.open('cominar'); db.execute('CREATE TABLE IF NOT EXISTS Ajax (AJAX_ID INTEGER PRIMARY KEY AUTOINCREMENT , MODULE TEXT, FUNCTION TEXT, CONTENT_JSON TEXT);'); db.execute('VACUUM;'); // nettoye la DB I'm trying to clean the database (VACUUM) the database at each initialisation but I get this error: Uncaught Error: Database operation failed. ERROR: authorization denied DETAILS: not authorized The database was created by me (the same page). Thank you!

    Read the article

  • VBA for Access 2003 - DDL help with creating access file: setting the Autonumber data type

    - by Justin
    So I have the below VB that creates an access file in the default workspace, creates a table, create some fields in that table...just need to know the syntax for setting the first data type/field to autonumber...GUID, Counter, etc will not work as in Access SQL ' error handling usually goes here dim ws as workspace dim dbExample as database dim tblMain as TableDef dim fldMain as Field dim idxMain as Index set ws = workspace(0) set dbExample = ws.CreateDatabase('string file path') set tblMain = dbExample.CreateTableDef("tblMain") set fldMain = tblMain.CreateField("ID", 'right here I do not know what to substitute for dbInteger to get the autonumber type to work ) tblMain.Fields.Append fldMain etc to create other fields and indexes so in this line: set fldMain = tblMain.CreateField("ID", dbInteger) i need to replace the dbInteger with something that VB reconizes as the autonumber property. i have tried GUID, Counter, Autonumber, AutoIncrement....unfortunately none of these work anyone know the syntax I am missing here? Thanks, Justin

    Read the article

  • Django BigInteger auto-increment field as primary key?

    - by Alex Letoosh
    Hi all, I'm currently building a project which involves a lot of collective intelligence. Every user visiting the web site gets created a unique profile and their data is later used to calculate best matches for themselves and other users. By default, Django creates an INT(11) id field to handle models primary keys. I'm concerned with this being overflown very quickly (i.e. ~2.4b devices visiting the page without prior cookie set up). How can I change it to be represented as BIGINT in MySQL and long() inside Django itself? I've found I could do the following (http://docs.djangoproject.com/en/dev/ref/models/fields/#bigintegerfield): class MyProfile(models.Model): id = BigIntegerField(primary_key=True) But is there a way to make it autoincrement, like usual id fields? Additionally, can I make it unsigned so that I get more space to fill in? Thanks!

    Read the article

  • Join query in doctrine symfony

    - by THOmas
    I have two tables userdetails and blog question The schema is UserDetails: connection: doctrine tableName: user_details columns: id: type: integer(8) fixed: false name: type: string(255) fixed: false BlogQuestion: connection: doctrine tableName: blog_question columns: question_id: type: integer(8) fixed: false unsigned: false primary: true autoincrement: true blog_id: type: integer(8) fixed: false user_id: type: integer(8) fixed: false question_title: type: string(255) I am using one join query for retrieving all the questions and user details from this two tables My join query is $q = Doctrine_Query::create() ->select('*') ->from('BlogQuestion u') ->leftJoin('u.UserDetails p'); $q->execute(); But it is showing this error Unknown relation alias UserDetails Pls anybody help me Thanks in advance

    Read the article

  • Create new field in a table that already exists - flex/air sqlite?

    - by Adam
    I've got a flex/air app I've been working on, it uses a local sqlite database that is created on the initial application start. I've added some features to the application and in the process I had to add a new field to one of the database tables. My questions is how to I go about getting the application to create one new field that is located in a table that already exists? this is a the line that creates the table stmt.text = "CREATE TABLE IF NOT EXISTS tbl_status ("+"status_id INTEGER PRIMARY KEY AUTOINCREMENT,"+" status_status TEXT)"; And now I'd like to add a status_default field. thanks! Thanks - MPelletier I've add the code you provided and it does add the field, but now the next time I restart my app I get an error - 'status_default' already exists'. So how can I go about adding some sort of a IF NOT EXISTS statement to the line you provided?

    Read the article

  • Attching a Behaviour to a dynamically created table in Doctrine

    - by Cesare Contini
    How do I programmatically attach a Doctrine Behaviour programmatically to a table dynamically created through $conn->export->createTable('MyTable', $definition)? For example, if I have the following code: $definition = array( 'id' => array( 'type' => 'integer', 'primary' => true, 'autoincrement' => true ), 'name' => array( 'type' => 'string', 'length' => 255 ) ); $conn->export->createTable('MyTable', $definition) ; At this point I would need to attach a doctrine typical behaviour like Timestampable or Versionable to the newly created 'MyTable' table. Is it possible at all?

    Read the article

  • How to create multiple tables with the same schema using SQLite jdbc

    - by Space_C0wb0y
    I want to split a large table horizontally, and I would like to make sure that all three of them have the same schema. Currently I am using this piece of code to create the tables: statement .executeUpdate("CREATE TABLE AnnotationsMolecularFunction (Id INTEGER PRIMARY KEY ASC AUTOINCREMENT, " + "ProteinId NOT NULL, " + "GOId NOT NULL, " + "UNIQUE (ProteinId, GOId)" + "FOREIGN KEY(ProteinId) REFERENCES Protein(Id))"); There is one such statement for each table. This is bad, because if I decide to change the schema later (which will most certainly happen), I will have to change it three times, which begs for errors, so I would like a way to make sure that the other tables have the same schema without explicitly writing it again. I can use: statement .executeUpdate("CREATE TABLE AnnotationsBiologicalProcess AS SELECT * FROM AnnotationsMolecularFunction"); to create the other tables with the same columns, but the constraints are not aplied. I could of course just generate the same query-string three times with different table-names in Java, but I would like to know if there is an SQL-way of achieving this.

    Read the article

  • how to build a index table(python dict like) in python with sqlite3

    - by Registered User KC
    Suppose I have one string list may have duplicated items: A B C A A C D E F F I want to make a list can assign an unique index for each item, looks like: 1 A 2 B 3 C 4 D 5 E 6 F now I created sqlite3 database with below SQL statement: CREATE TABLE aa ( myid INTEGER PRIMARY KEY AUTOINCREMENT, name STRING, UNIQUE (myid) ON CONFLICT FAIL, UNIQUE (name) ON CONFLICT FAIL); The plan is insert each row into the database in python. My question is how to handle the error when conflict do happened when insert in python module sqlite3? For example: the program will printing a warning message which item is conflicted and continue next insert action when inserting in python? Thanks

    Read the article

  • sqlite ERROR no such column

    - by Richard
    Hi, Does anyone here have some experience with this error? Only If I use the WHERE clause, I get this error. I use php PDO to get the results. And this is my simple table $sql = "CREATE TABLE samenvatting ( stem_id INTEGER PRIMARY KEY AUTOINCREMENT, poll_id TEXT, stem_waarde_id TEXT, totaal INTEGER )"; $crud->rawQuery($sql); $poll_id = "somepoll"; $records = $crud->rawSelect('SELECT * FROM samenvatting WHERE poll_id=´.$poll_id); pdo abstract class public function conn() { isset($this->username); isset($this->password); if (!$this->db instanceof PDO) { $this->db = new PDO($this->dsn, $this->username, $this->password); $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } } public function rawSelect($sql) { $this->conn(); return $this->db->query($sql); } Thanks, Richard

    Read the article

  • Is there any way to simplify a verbose SQL INSERT INTO(..) query?

    - by Soundar Rajan
    I have a table with one id (autonumber) field and 50 other fields. The table is normalized, these are 50 material properties etc. I want to copy a record from this table into the same table - only the autoincrement id will be different. The query I am using now is INSERT INTO tableName (field1,field2,....field50) SELECT field1,field2,....field50 from tableName WHERE autoid=1234; Note that I have to type in ALL the 50 field names, twice! Is there any way to shorten this query so I don't have to type all of them? Thanks.

    Read the article

  • Handle ConstraintException and get ColumnName that cause the error

    - by Mysterious
    Hello, I have a Table Machines that made of: ID = Identity , Primary , AutoIncrement,NOT NULL SN = Unique , String , NOT NULL Name =String now I am using a form to insert data into this table, and I am using BindingSource and ErrorProvider, I am handling Null and Empty string in the DataSet layer (partial class in the dataset.xsd), now when I try to end editing this.machinesBindingSource.EndEdit(); I got this error message: ex.Message = "Column 'SN' is constrained to be unique. Value '123' is already present." I know I entered a duplicated value but the question is HOW can I determine which the columnName that cause the error and re-write the error message entirely in different language I want to get the columnName and the wrong value thanks in advance

    Read the article

  • SQLserver multithreaded locking with TABLOCKX

    - by WilfriedVS
    I have a table "tbluser" with 2 fields: userid = integer (autoincrement) user = nvarchar(100) I have a multithreaded/multi server application that uses this table. I want to accomplish the following: Guarantee that field user is unique in my table Guarantee that combination userid/user is unique in each server's memory I have the following stored procedure: CREATE PROCEDURE uniqueuser @user nvarchar(100) AS BEGIN BEGIN TRAN DECLARE @userID int SET nocount ON SET @userID = (SELECT @userID FROM tbluser WITH (TABLOCKX) WHERE [user] = @user) IF @userID <> '' BEGIN SELECT userID = @userID END ELSE BEGIN INSERT INTO tbluser([user]) VALUES (@user) SELECT userID = SCOPE_IDENTITY() END COMMIT TRAN END Basically the application calls the stored procedure and provides a username as parameter. The stored procedure either gets the userid or insert the user if it is a new user. Am I correct to assume that the table is locked (only one server can insert/query)?

    Read the article

  • Implement subitem in SQLite

    - by Mohit Deshpande
    How could I implement a sub item where the item would have a parent to that of the same item. For example, I have a database that holds tasks/todos. Each todo has a title(TEXT), completed(INTEGER [1 if true, 0 if false]), and due date(TEXT) column. I would like to add functionality to have subtasks, where a task could possibly have a parent task. How would I implement this in SQLite for Android? NOT IN SQL! So no foreign keys (triggers are allow, though)! Could I just have a separate table (subtask) and have a foreign key trigger to link subtask(INTEGER parent) to task(INTEGER PRIMARY KEY AUTOINCREMENT _id)? Or should I add a column to my original task table(INTEGER parent)? How could I implement this?

    Read the article

  • Referencing file on disk from NSManagedObject

    - by Kamchatka
    Hello, What would be the best way to name a file associated to a NSManagedObject. The NSManagedObject will hold the URL to this file. But I need to create a unique filename for my file. Is there some kind of autoincrement id that I could use? Should I use mktemp (but it's not a temporary file) or try to convert the NSManagedObjectId to a filename? but I fear there will be special characters which might cause problem. What would you suggest?

    Read the article

  • Model-layer validation in Doctrine, Symfony

    - by Andree
    Hi there, I have a schema.yml containing something similiar to the following: Character: tableName: characters actAs: { Timestampable: ~ } columns: id: { type: integer(4), primary: true, autoincrement: true } name: { type: string(255), notnull: true, notblank: true, minlength: 3 } I define the minlength of the column name to be 3. I created a unit test to test the minlength validation, and I found out that the validation is not working. $character = new Character(); $character->set('name', 'Dw'); $t->ok(! $character->isValid()); # This test failed Can someone tell me what might be the problem here? Thanks, Andree

    Read the article

  • Copying Data between table without identity column

    - by user668479
    I have two table and I need to copy the data across from SRCServiceUsers to Clients Everytime i run it I get the following: Violation of PRIMARY KEY constraint 'PK_Clients'. Cannot insert duplicate key in object 'dbo.Clients'. The statement has been terminated. The Primary key ClientId field is not an identity column and therefore requires filling To date I have the following insert into Clients( ClientID, Title, Forenames, FamilyName, [Address], Town, County, PostCode, PhoneNumber, StartDate) SELECT ( Select Max(Clients.ClientID)+ 1, SRCServiceUsers.Title, SRCServiceUsers.[First Names], SRCServiceUsers.Surname, --BUILD UP MUITIPLE COLUMNS SRCServiceUsers.[Property Name] + ', ' + SRCServiceUsers.Street + ', ' + SRCServiceUsers.Suburb as [Address], SRCServiceUsers.Town, SRCServiceUsers.County, SRCServiceUsers.Postcode, SRCServiceUsers.Telephone, SRCServiceUsers.[Start Date] From srcsERVICEuSERS How can i autoincrement the PK field - CLientID when inserting the data? Many thanks Andrew

    Read the article

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