Search Results

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

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

  • Renaming column in Android sqlite database results in error

    - by Apophenia Overload
    I've been modifying the Notepad tutorial for Android very subtly- all I did was rename the column from title to name: Before: public static final String KEY_TITLE = "title"; ... private static final String DATABASE_CREATE = "create table notes (_id integer primary key autoincrement, " + "title text not null, body text not null);"; After: public static final String KEY_TITLE = "name"; ... private static final String DATABASE_CREATE = "create table notes (_id integer primary key autoincrement, " + "name text not null, body text not null);"; However, it always results in this: 06-10 03:29:38.421: ERROR/AndroidRuntime(344): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.demo.notepad1/com.android.demo.notepad1.Notepadv1}: android.database.sqlite.SQLiteException: no such column: name: , while compiling: SELECT _id, name, body FROM notes ... 06-10 03:29:38.421: ERROR/AndroidRuntime(344): Caused by: android.database.sqlite.SQLiteException: no such column: name: , while compiling: SELECT _id, name, body FROM notes Am I failing to rename something? All I am modifying is the Exercise 1 Solution program from the Notepad tutorial.

    Read the article

  • DBD::SQLite::st execute failed: datatype mismatch

    - by Barton Chittenden
    Here's a snippit of perl code: sub insert_timesheet { my $dbh = shift; my $entryref = shift; my $insertme = join(',', @_); my $values_template = '?, ' x scalar(@_); chop $values_template; chop $values_template; #remove trailing comma my $insert = "INSERT INTO timesheet( $insertme ) VALUES ( $values_template );"; my $sth = $dbh->prepare($insert); debug("$insert"); my @values; foreach my $entry (@_){ push @values, $$entryref{$entry} } debug("@values"); my $rv = $sth->execute( @values ) or die $dbh->errstr; debug("sql return value: $rv"); $dbh->disconnect; } The value of $insert: [INSERT INTO timesheet( idx,Start_Time,End_Time,Project,Ticket_Number,Site,Duration,Notes ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ? );] Here are @values: [null '1270950742' '1270951642' 'asdf' 'asdf' 'adsf' 15 ''] Here's the schema of 'timesheet' timesheet( idx INTEGER PRIMARY KEY AUTOINCREMENT, Start_Time VARCHAR, End_Time VARCHAR, Duration INTEGER, Project VARCHAR, Ticket_Number VARCHAR, Site VARCHAR, Notes VARCHAR) Here's how things line up: ---- Insert Statement Schema @values ---- idx idx INTEGER PRIMARY KEY AUTOINCREMENT null: # this is not a mismatch, passing null will allow auto-increment. Start_Time Start_Time VARCHAR '1270950742' End_Time End_Time VARCHAR '1270951642' Project Project VARCHAR 'asdf' Ticket_Number Ticket_Number VARCHAR 'asdf' Site Site VARCHAR 'adsf' Duration Duration INTEGER 15 Notes Notes VARCHAR '' ... I can't see the data-type mis-match.

    Read the article

  • SQLAlchemy: select over multiple tables

    - by ahojnnes
    Hi, I wanted to optimize my database query: link_list = select( columns=[link_table.c.rating, link_table.c.url, link_table.c.donations_in], whereclause=and_( not_(link_table.c.id.in_( select( columns=[request_table.c.recipient], whereclause=request_table.c.donator==donator.id ).as_scalar() )), link_table.c.id!=donator.id, ), limit=20, ).execute().fetchall() and tried to merge those two selects in one query: link_list = select( columns=[link_table.c.rating, link_table.c.url, link_table.c.donations_in], whereclause=and_( link_table.c.active==True, link_table.c.id!=donator.id, request_table.c.donator==donator.id, link_table.c.id!=request_table.c.recipient, ), limit=20, order_by=[link_table.c.rating.desc()] ).execute().fetchall() the database-schema looks like: link_table = Table('links', metadata, Column('id', Integer, primary_key=True, autoincrement=True), Column('url', Unicode(250), index=True, unique=True), Column('registration_date', DateTime), Column('donations_in', Integer), Column('active', Boolean), ) request_table = Table('requests', metadata, Column('id', Integer, primary_key=True, autoincrement=True), Column('recipient', Integer, ForeignKey('links.id')), Column('donator', Integer, ForeignKey('links.id')), Column('date', DateTime), ) There are several links (donator) in request_table pointing to one link in the link_table. I want to have links from link_table, which are not yet "requested". But this does not work. Is it actually possible, what I'm trying to do? If so, how would you do that? Thank you very much in advance!

    Read the article

  • one table is shared between several websites

    - by sami
    I have a static table that's shared by several websites. By static, I mean that the data is read but never updated by the websites. Currently, all websites are served from the same server but that may change. I want to minimize the need for creating/maintaining this table for each of the websites, so I thought about turning it to an xml file that's stored in a shared library that all websites have access to. The problem is I use an ORM and use forign key constraints to ensure integrity of the ids used from that table, so by removing that table out of the MySQL database into an XML file, will this affect the integrity of the ids coming from that table? My table looks like this <table name="entry"> <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true" /> <column name="title" type="VARCHAR" size="500" required="true" /> </table> and I use it as a foreign key in other tables <table name="refer"> <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true" /> <column name="linkto" type="INTEGER"/> <foreign-key foreignTable="entry"> <reference local="linkto" foreign="id" /> </foreign-key> </table> So I'm wondering if I remove that table out of the database, is there a way to retain that referential integrity? And of course are these any other efficient ways to do the same thing? I just don't want to have to repeat that table for several websites.

    Read the article

  • Metro Walkthrough: Creating a Task List with a ListView and IndexedDB

    - by Stephen.Walther
    The goal of this blog entry is to describe how you can work with data in a Metro style application written with JavaScript. In particular, we create a super simple Task List application which enables you to create and delete tasks. Here’s a video which demonstrates how the Task List application works: In order to build this application, I had to take advantage of several features of the WinJS library and technologies including: IndexedDB – The Task List application stores data in an IndexedDB database. HTML5 Form Validation – The Task List application uses HTML5 validation to ensure that a required field has a value. ListView Control – The Task List application displays the tasks retrieved from the IndexedDB database in a WinJS ListView control. Creating the IndexedDB Database The Task List application stores all of its data in an IndexedDB database named TasksDB. This database is opened/created with the following code: var db; var req = window.msIndexedDB.open("TasksDB", 1); req.onerror = function () { console.log("Could not open database"); }; req.onupgradeneeded = function (evt) { var newDB = evt.target.result; newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement:true }); }; The msIndexedDB.open() method accepts two parameters: the name of the database to open and the version of the database to open. If a database with a matching version already exists, then calling the msIndexedDB.open() method opens a connection to the existing database. If the database does not exist then the upgradeneeded event is raised. You handle the upgradeneeded event to create a new database. In the code above, the upgradeneeded event handler creates an object store named “tasks” (An object store roughly corresponds to a database table). When you add items to the tasks object store then each item gets an id property with an auto-incremented value automatically. The code above also includes an error event handler. If the IndexedDB database cannot be opened or created, for whatever reason, then an error message is written to the Visual Studio JavaScript Console window. Displaying a List of Tasks The TaskList application retrieves its list of tasks from the tasks object store, which we created above, and displays the list of tasks in a ListView control. Here is how the ListView control is declared: <div id="tasksListView" data-win-control="WinJS.UI.ListView" data-win-options="{ itemDataSource: TaskList.tasks.dataSource, itemTemplate: select('#taskTemplate'), tapBehavior: 'toggleSelect', selectionMode: 'multi', layout: { type: WinJS.UI.ListLayout } }"> </div> The ListView control is bound to the TaskList.tasks.dataSource data source. The TaskList.tasks.dataSource is created with the following code: // Create the data source var tasks = new WinJS.Binding.List(); // Open the database var db; var req = window.msIndexedDB.open("TasksDB", 1); req.onerror = function () { console.log("Could not open database"); }; req.onupgradeneeded = function (evt) { var newDB = evt.target.result; newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement:true }); }; // Load the data source with data from the database req.onsuccess = function () { db = req.result; var tran = db.transaction("tasks"); tran.objectStore("tasks").openCursor().onsuccess = function(event) { var cursor = event.target.result; if (cursor) { tasks.dataSource.insertAtEnd(null, cursor.value); cursor.continue(); }; }; }; // Expose the data source and functions WinJS.Namespace.define("TaskList", { tasks: tasks }); Notice the success event handler. This handler is called when a database is successfully opened/created. In the code above, all of the items from the tasks object store are retrieved into a cursor and added to a WinJS.Binding.List object named tasks. Because the ListView control is bound to the WinJS.Binding.List object, copying the tasks from the object store into the WinJS.Binding.List object causes the tasks to appear in the ListView: Adding a New Task You add a new task in the Task List application by entering the title of a new task into an HTML form and clicking the Add button. Here’s the markup for creating the form: <form id="addTaskForm"> <input id="newTaskTitle" title="New Task" required /> <button>Add</button> </form> Notice that the INPUT element includes a required attribute. In a Metro application, you can take advantage of HTML5 Validation to validate form fields. If you don’t enter a value for the newTaskTitle field then the following validation error message is displayed: For a brief introduction to HTML5 validation, see my previous blog entry: http://stephenwalther.com/blog/archive/2012/03/13/html5-form-validation.aspx When you click the Add button, the form is submitted and the form submit event is raised. The following code is executed in the default.js file: // Handle Add Task document.getElementById("addTaskForm").addEventListener("submit", function (evt) { evt.preventDefault(); var newTaskTitle = document.getElementById("newTaskTitle"); TaskList.addTask({ title: newTaskTitle.value }); newTaskTitle.value = ""; }); The code above retrieves the title of the new task and calls the addTask() method in the tasks.js file. Here’s the code for the addTask() method which is responsible for actually adding the new task to the IndexedDB database: // Add a new task function addTask(taskToAdd) { var transaction = db.transaction("tasks", "readwrite"); var addRequest = transaction.objectStore("tasks").add(taskToAdd); addRequest.onsuccess = function (evt) { taskToAdd.id = evt.target.result; tasks.dataSource.insertAtEnd(null, taskToAdd); } } The code above does two things. First, it adds the new task to the tasks object store in the IndexedDB database. Second, it adds the new task to the data source bound to the ListView. The dataSource.insertAtEnd() method is called to add the new task to the data source so the new task will appear in the ListView (with a nice little animation). Deleting Existing Tasks The Task List application enables you to select one or more tasks by clicking or tapping on one or more tasks in the ListView. When you click the Delete button, the selected tasks are removed from both the IndexedDB database and the ListView. For example, in the following screenshot, two tasks are selected. The selected tasks appear with a teal background and a checkmark: When you click the Delete button, the following code in the default.js file is executed: // Handle Delete Tasks document.getElementById("btnDeleteTasks").addEventListener("click", function (evt) { tasksListView.winControl.selection.getItems().then(function(items) { items.forEach(function (item) { TaskList.deleteTask(item); }); }); }); The selected tasks are retrieved with the TaskList selection.getItem() method. In the code above, the deleteTask() method is called for each of the selected tasks. Here’s the code for the deleteTask() method: // Delete an existing task function deleteTask(listViewItem) { // Database key != ListView key var dbKey = listViewItem.data.id; var listViewKey = listViewItem.key; // Remove item from db and, if success, remove item from ListView var transaction = db.transaction("tasks", “readwrite”); var deleteRequest = transaction.objectStore("tasks").delete(dbKey); deleteRequest.onsuccess = function () { tasks.dataSource.remove(listViewKey); } } This code does two things: it deletes the existing task from the database and removes the existing task from the ListView. In both cases, the right task is removed by using the key associated with the task. However, the task key is different in the case of the database and in the case of the ListView. In the case of the database, the task key is the value of the task id property. In the case of the ListView, on the other hand, the task key is auto-generated by the ListView. When the task is removed from the ListView, an animation is used to collapse the tasks which appear above and below the task which was removed. The Complete Code Above, I did a lot of jumping around between different files in the application and I left out sections of code. For the sake of completeness, I want to include the entire code here: the default.html, default.js, and tasks.js files. Here are the contents of the default.html file. This file contains the UI for the Task List application: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Task List</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"> <script src="//Microsoft.WinJS.0.6/js/base.js"></script> <script src="//Microsoft.WinJS.0.6/js/ui.js"></script> <!-- TaskList references --> <link href="/css/default.css" rel="stylesheet"> <script src="/js/default.js"></script> <script type="text/javascript" src="js/tasks.js"></script> <style type="text/css"> body { font-size: x-large; } form { display: inline; } #appContainer { margin: 20px; width: 600px; } .win-container { padding: 10px; } </style> </head> <body> <div> <!-- Templates --> <div id="taskTemplate" data-win-control="WinJS.Binding.Template"> <div> <span data-win-bind="innerText:title"></span> </div> </div> <h1>Super Task List</h1> <div id="appContainer"> <form id="addTaskForm"> <input id="newTaskTitle" title="New Task" required /> <button>Add</button> </form> <button id="btnDeleteTasks">Delete</button> <div id="tasksListView" data-win-control="WinJS.UI.ListView" data-win-options="{ itemDataSource: TaskList.tasks.dataSource, itemTemplate: select('#taskTemplate'), tapBehavior: 'toggleSelect', selectionMode: 'multi', layout: { type: WinJS.UI.ListLayout } }"> </div> </div> </div> </body> </html> Here is the code for the default.js file. This code wires up the Add Task form and Delete button: (function () { "use strict"; var app = WinJS.Application; app.onactivated = function (eventObject) { if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) { WinJS.UI.processAll().then(function () { // Get reference to Tasks ListView var tasksListView = document.getElementById("tasksListView"); // Handle Add Task document.getElementById("addTaskForm").addEventListener("submit", function (evt) { evt.preventDefault(); var newTaskTitle = document.getElementById("newTaskTitle"); TaskList.addTask({ title: newTaskTitle.value }); newTaskTitle.value = ""; }); // Handle Delete Tasks document.getElementById("btnDeleteTasks").addEventListener("click", function (evt) { tasksListView.winControl.selection.getItems().then(function(items) { items.forEach(function (item) { TaskList.deleteTask(item); }); }); }); }); } }; app.start(); })(); Finally, here is the tasks.js file. This file contains all of the code for opening, creating, and interacting with IndexedDB: (function () { "use strict"; // Create the data source var tasks = new WinJS.Binding.List(); // Open the database var db; var req = window.msIndexedDB.open("TasksDB", 1); req.onerror = function () { console.log("Could not open database"); }; req.onupgradeneeded = function (evt) { var newDB = evt.target.result; newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement:true }); }; // Load the data source with data from the database req.onsuccess = function () { db = req.result; var tran = db.transaction("tasks"); tran.objectStore("tasks").openCursor().onsuccess = function(event) { var cursor = event.target.result; if (cursor) { tasks.dataSource.insertAtEnd(null, cursor.value); cursor.continue(); }; }; }; // Add a new task function addTask(taskToAdd) { var transaction = db.transaction("tasks", "readwrite"); var addRequest = transaction.objectStore("tasks").add(taskToAdd); addRequest.onsuccess = function (evt) { taskToAdd.id = evt.target.result; tasks.dataSource.insertAtEnd(null, taskToAdd); } } // Delete an existing task function deleteTask(listViewItem) { // Database key != ListView key var dbKey = listViewItem.data.id; var listViewKey = listViewItem.key; // Remove item from db and, if success, remove item from ListView var transaction = db.transaction("tasks", "readwrite"); var deleteRequest = transaction.objectStore("tasks").delete(dbKey); deleteRequest.onsuccess = function () { tasks.dataSource.remove(listViewKey); } } // Expose the data source and functions WinJS.Namespace.define("TaskList", { tasks: tasks, addTask: addTask, deleteTask: deleteTask }); })(); Summary I wrote this blog entry because I wanted to create a walkthrough of building a simple database-driven application. In particular, I wanted to demonstrate how you can use a ListView control with an IndexedDB database to store and retrieve database data.

    Read the article

  • Metro Walkthrough: Creating a Task List with a ListView and IndexedDB

    - by Stephen.Walther
    The goal of this blog entry is to describe how you can work with data in a Metro style application written with JavaScript. In particular, we create a super simple Task List application which enables you to create and delete tasks. Here’s a video which demonstrates how the Task List application works: In order to build this application, I had to take advantage of several features of the WinJS library and technologies including: IndexedDB – The Task List application stores data in an IndexedDB database. HTML5 Form Validation – The Task List application uses HTML5 validation to ensure that a required field has a value. ListView Control – The Task List application displays the tasks retrieved from the IndexedDB database in a WinJS ListView control. Creating the IndexedDB Database The Task List application stores all of its data in an IndexedDB database named TasksDB. This database is opened/created with the following code: var db; var req = window.msIndexedDB.open("TasksDB", 1); req.onerror = function () { console.log("Could not open database"); }; req.onupgradeneeded = function (evt) { var newDB = evt.target.result; newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement:true }); }; The msIndexedDB.open() method accepts two parameters: the name of the database to open and the version of the database to open. If a database with a matching version already exists, then calling the msIndexedDB.open() method opens a connection to the existing database. If the database does not exist then the upgradeneeded event is raised. You handle the upgradeneeded event to create a new database. In the code above, the upgradeneeded event handler creates an object store named “tasks” (An object store roughly corresponds to a database table). When you add items to the tasks object store then each item gets an id property with an auto-incremented value automatically. The code above also includes an error event handler. If the IndexedDB database cannot be opened or created, for whatever reason, then an error message is written to the Visual Studio JavaScript Console window. Displaying a List of Tasks The TaskList application retrieves its list of tasks from the tasks object store, which we created above, and displays the list of tasks in a ListView control. Here is how the ListView control is declared: <div id="tasksListView" data-win-control="WinJS.UI.ListView" data-win-options="{ itemDataSource: TaskList.tasks.dataSource, itemTemplate: select('#taskTemplate'), tapBehavior: 'toggleSelect', selectionMode: 'multi', layout: { type: WinJS.UI.ListLayout } }"> </div> The ListView control is bound to the TaskList.tasks.dataSource data source. The TaskList.tasks.dataSource is created with the following code: // Create the data source var tasks = new WinJS.Binding.List(); // Open the database var db; var req = window.msIndexedDB.open("TasksDB", 1); req.onerror = function () { console.log("Could not open database"); }; req.onupgradeneeded = function (evt) { var newDB = evt.target.result; newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement:true }); }; // Load the data source with data from the database req.onsuccess = function () { db = req.result; var tran = db.transaction("tasks"); tran.objectStore("tasks").openCursor().onsuccess = function(event) { var cursor = event.target.result; tasks.dataSource.beginEdits(); if (cursor) { tasks.dataSource.insertAtEnd(null, cursor.value); cursor.continue(); } else { tasks.dataSource.endEdits(); }; }; }; // Expose the data source and functions WinJS.Namespace.define("TaskList", { tasks: tasks }); Notice the success event handler. This handler is called when a database is successfully opened/created. In the code above, all of the items from the tasks object store are retrieved into a cursor and added to a WinJS.Binding.List object named tasks. Because the ListView control is bound to the WinJS.Binding.List object, copying the tasks from the object store into the WinJS.Binding.List object causes the tasks to appear in the ListView: Adding a New Task You add a new task in the Task List application by entering the title of a new task into an HTML form and clicking the Add button. Here’s the markup for creating the form: <form id="addTaskForm"> <input id="newTaskTitle" title="New Task" required /> <button>Add</button> </form> Notice that the INPUT element includes a required attribute. In a Metro application, you can take advantage of HTML5 Validation to validate form fields. If you don’t enter a value for the newTaskTitle field then the following validation error message is displayed: For a brief introduction to HTML5 validation, see my previous blog entry: http://stephenwalther.com/blog/archive/2012/03/13/html5-form-validation.aspx When you click the Add button, the form is submitted and the form submit event is raised. The following code is executed in the default.js file: // Handle Add Task document.getElementById("addTaskForm").addEventListener("submit", function (evt) { evt.preventDefault(); var newTaskTitle = document.getElementById("newTaskTitle"); TaskList.addTask({ title: newTaskTitle.value }); newTaskTitle.value = ""; }); The code above retrieves the title of the new task and calls the addTask() method in the tasks.js file. Here’s the code for the addTask() method which is responsible for actually adding the new task to the IndexedDB database: // Add a new task function addTask(taskToAdd) { var transaction = db.transaction("tasks", IDBTransaction.READ_WRITE); var addRequest = transaction.objectStore("tasks").add(taskToAdd); addRequest.onsuccess = function (evt) { taskToAdd.id = evt.target.result; tasks.dataSource.insertAtEnd(null, taskToAdd); } } The code above does two things. First, it adds the new task to the tasks object store in the IndexedDB database. Second, it adds the new task to the data source bound to the ListView. The dataSource.insertAtEnd() method is called to add the new task to the data source so the new task will appear in the ListView (with a nice little animation). Deleting Existing Tasks The Task List application enables you to select one or more tasks by clicking or tapping on one or more tasks in the ListView. When you click the Delete button, the selected tasks are removed from both the IndexedDB database and the ListView. For example, in the following screenshot, two tasks are selected. The selected tasks appear with a teal background and a checkmark: When you click the Delete button, the following code in the default.js file is executed: // Handle Delete Tasks document.getElementById("btnDeleteTasks").addEventListener("click", function (evt) { tasksListView.winControl.selection.getItems().then(function(items) { items.forEach(function (item) { TaskList.deleteTask(item); }); }); }); The selected tasks are retrieved with the TaskList selection.getItem() method. In the code above, the deleteTask() method is called for each of the selected tasks. Here’s the code for the deleteTask() method: // Delete an existing task function deleteTask(listViewItem) { // Database key != ListView key var dbKey = listViewItem.data.id; var listViewKey = listViewItem.key; // Remove item from db and, if success, remove item from ListView var transaction = db.transaction("tasks", IDBTransaction.READ_WRITE); var deleteRequest = transaction.objectStore("tasks").delete(dbKey); deleteRequest.onsuccess = function () { tasks.dataSource.remove(listViewKey); } } This code does two things: it deletes the existing task from the database and removes the existing task from the ListView. In both cases, the right task is removed by using the key associated with the task. However, the task key is different in the case of the database and in the case of the ListView. In the case of the database, the task key is the value of the task id property. In the case of the ListView, on the other hand, the task key is auto-generated by the ListView. When the task is removed from the ListView, an animation is used to collapse the tasks which appear above and below the task which was removed. The Complete Code Above, I did a lot of jumping around between different files in the application and I left out sections of code. For the sake of completeness, I want to include the entire code here: the default.html, default.js, and tasks.js files. Here are the contents of the default.html file. This file contains the UI for the Task List application: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Task List</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"> <script src="//Microsoft.WinJS.0.6/js/base.js"></script> <script src="//Microsoft.WinJS.0.6/js/ui.js"></script> <!-- TaskList references --> <link href="/css/default.css" rel="stylesheet"> <script src="/js/default.js"></script> <script type="text/javascript" src="js/tasks.js"></script> <style type="text/css"> body { font-size: x-large; } form { display: inline; } #appContainer { margin: 20px; width: 600px; } .win-container { padding: 10px; } </style> </head> <body> <div> <!-- Templates --> <div id="taskTemplate" data-win-control="WinJS.Binding.Template"> <div> <span data-win-bind="innerText:title"></span> </div> </div> <h1>Super Task List</h1> <div id="appContainer"> <form id="addTaskForm"> <input id="newTaskTitle" title="New Task" required /> <button>Add</button> </form> <button id="btnDeleteTasks">Delete</button> <div id="tasksListView" data-win-control="WinJS.UI.ListView" data-win-options="{ itemDataSource: TaskList.tasks.dataSource, itemTemplate: select('#taskTemplate'), tapBehavior: 'toggleSelect', selectionMode: 'multi', layout: { type: WinJS.UI.ListLayout } }"> </div> </div> </div> </body> </html> Here is the code for the default.js file. This code wires up the Add Task form and Delete button: (function () { "use strict"; var app = WinJS.Application; app.onactivated = function (eventObject) { if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) { WinJS.UI.processAll().then(function () { // Get reference to Tasks ListView var tasksListView = document.getElementById("tasksListView"); // Handle Add Task document.getElementById("addTaskForm").addEventListener("submit", function (evt) { evt.preventDefault(); var newTaskTitle = document.getElementById("newTaskTitle"); TaskList.addTask({ title: newTaskTitle.value }); newTaskTitle.value = ""; }); // Handle Delete Tasks document.getElementById("btnDeleteTasks").addEventListener("click", function (evt) { tasksListView.winControl.selection.getItems().then(function(items) { items.forEach(function (item) { TaskList.deleteTask(item); }); }); }); }); } }; app.start(); })(); Finally, here is the tasks.js file. This file contains all of the code for opening, creating, and interacting with IndexedDB: (function () { "use strict"; // Create the data source var tasks = new WinJS.Binding.List(); // Open the database var db; var req = window.msIndexedDB.open("TasksDB", 1); req.onerror = function () { console.log("Could not open database"); }; req.onupgradeneeded = function (evt) { var newDB = evt.target.result; newDB.createObjectStore("tasks", { keyPath: "id", autoIncrement:true }); }; // Load the data source with data from the database req.onsuccess = function () { db = req.result; var tran = db.transaction("tasks"); tran.objectStore("tasks").openCursor().onsuccess = function(event) { var cursor = event.target.result; tasks.dataSource.beginEdits(); if (cursor) { tasks.dataSource.insertAtEnd(null, cursor.value); cursor.continue(); } else { tasks.dataSource.endEdits(); }; }; }; // Add a new task function addTask(taskToAdd) { var transaction = db.transaction("tasks", IDBTransaction.READ_WRITE); var addRequest = transaction.objectStore("tasks").add(taskToAdd); addRequest.onsuccess = function (evt) { taskToAdd.id = evt.target.result; tasks.dataSource.insertAtEnd(null, taskToAdd); } } // Delete an existing task function deleteTask(listViewItem) { // Database key != ListView key var dbKey = listViewItem.data.id; var listViewKey = listViewItem.key; // Remove item from db and, if success, remove item from ListView var transaction = db.transaction("tasks", IDBTransaction.READ_WRITE); var deleteRequest = transaction.objectStore("tasks").delete(dbKey); deleteRequest.onsuccess = function () { tasks.dataSource.remove(listViewKey); } } // Expose the data source and functions WinJS.Namespace.define("TaskList", { tasks: tasks, addTask: addTask, deleteTask: deleteTask }); })(); Summary I wrote this blog entry because I wanted to create a walkthrough of building a simple database-driven application. In particular, I wanted to demonstrate how you can use a ListView control with an IndexedDB database to store and retrieve database data.

    Read the article

  • symfony/propel: problem trying to add a new object action in a backend module

    - by user248959
    Hi, i have created this model: propel: shop_orders: orders_id: { phpName: Id, type: INTEGER, size: '11', primaryKey: true, autoIncrement: true, required: true } email: { type: VARCHAR, size: '45', required: true } Then i have generated an admin module and i have add this below to generator.yml: config: actions: ~ fields: ~ list: object_actions: foo: {} When I click on the foo action It generates this url: backend_dev.php/sp1/ListFoo/action?id=1 and I get this message: Action "sp1/action" does not exist. sf 1.4/propel Any idea? Javier

    Read the article

  • DataRelation Insert and ForeignKey

    - by Steve
    Guys, I have a winforms application with two DataGridViews displaying a master-detail relationship from my Person and Address tables. Person table has a PersonID field that is auto-incrementing primary key. Address has a PersonID field that is the FK. I fill my DataTables with DataAdapter and set Person.PersonID column's AutoIncrement=true and AutoIncrementStep=-1. I can insert records in the Person DataTable from the DataGridView. The PersonID column displays unique negative values for PersonID. I update the database by calling DataAdapter.Update(PersonTable) and the negative PersonIDs are converted to positive unique values automatically by SQL Server. Here's the rub. The Address DataGridView show the address table which has a DataRelation to Person by PersonID. Inserted Person records have the temporary negative PersonID. I can now insert records into Address via DataGridView and Address.PersonID is set to the negative value from the DataRelation mapping. I call Adapter.Update(AddressTable) and the negative PersonIDs go into the Address table breaking the relationship. How do you guys handle primary/foreign keys using DataTables and master-detail DataGridViews? Thanks! Steve EDIT: After more googling, I found that SqlDataAdapter.RowUpdated event gives me what I need. I create a new command to query the last id inserted by using @@IDENTITY. It works pretty well. The DataRelation updates the Address.PersonID field for me so it's required to Update the Person table first then update the Address table. All the new records insert properly with correct ids in place! Adapter = new SqlDataAdapter(cmd); Adapter.RowUpdated += (s, e) => { if (e.StatementType != StatementType.Insert) return; //set the id for the inserted record SqlCommand c = e.Command.Connection.CreateCommand(); c.CommandText = "select @@IDENTITY id"; e.Row[0] = Convert.ToInt32( c.ExecuteScalar() ); }; Adapter.Fill(this); SqlCommandBuilder sb = new SqlCommandBuilder(Adapter); sb.GetDeleteCommand(); sb.GetUpdateCommand(); sb.GetInsertCommand(); this.Columns[0].AutoIncrement = true; this.Columns[0].AutoIncrementSeed = -1; this.Columns[0].AutoIncrementStep = -1;

    Read the article

  • INSERT OR IGNORE in a trigger

    - by dan04
    I have a database (for tracking email statistics) that has grown to hundreds of megabytes, and I've been looking for ways to reduce it. It seems that the main reason for the large file size is that the same strings tend to be repeated in thousands of rows. To avoid this problem, I plan to create another table for a string pool, like so: CREATE TABLE AddressLookup ( ID INTEGER PRIMARY KEY AUTOINCREMENT, Address TEXT UNIQUE ); CREATE TABLE EmailInfo ( MessageID INTEGER PRIMARY KEY AUTOINCREMENT, ToAddrRef INTEGER REFERENCES AddressLookup(ID), FromAddrRef INTEGER REFERENCES AddressLookup(ID) /* Additional columns omitted for brevity. */ ); And for convenience, a view to join these tables: CREATE VIEW EmailView AS SELECT MessageID, A1.Address AS ToAddr, A2.Address AS FromAddr FROM EmailInfo LEFT JOIN AddressLookup A1 ON (ToAddrRef = A1.ID) LEFT JOIN AddressLookup A2 ON (FromAddrRef = A2.ID); In order to be able to use this view as if it were a regular table, I've made some triggers: CREATE TRIGGER trg_id_EmailView INSTEAD OF DELETE ON EmailView BEGIN DELETE FROM EmailInfo WHERE MessageID = OLD.MessageID; END; CREATE TRIGGER trg_ii_EmailView INSTEAD OF INSERT ON EmailView BEGIN INSERT OR IGNORE INTO AddressLookup(Address) VALUES (NEW.ToAddr); INSERT OR IGNORE INTO AddressLookup(Address) VALUES (NEW.FromAddr); INSERT INTO EmailInfo SELECT NEW.MessageID, A1.ID, A2.ID FROM AddressLookup A1, AddressLookup A2 WHERE A1.Address = NEW.ToAddr AND A2.Address = NEW.FromAddr; END; CREATE TRIGGER trg_iu_EmailView INSTEAD OF UPDATE ON EmailView BEGIN UPDATE EmailInfo SET MessageID = NEW.MessageID WHERE MessageID = OLD.MessageID; REPLACE INTO EmailView SELECT NEW.MessageID, NEW.ToAddr, NEW.FromAddr; END; The problem After: INSERT OR REPLACE INTO EmailView VALUES (1, '[email protected]', '[email protected]'); INSERT OR REPLACE INTO EmailView VALUES (2, '[email protected]', '[email protected]'); The updated rows contain: MessageID ToAddr FromAddr --------- ------ -------- 1 NULL [email protected] 2 [email protected] [email protected] There's a NULL that shouldn't be there. The corresponding cell in the EmailInfo table contains an orphaned ToAddrRef value. If you do the INSERTs one at a time, you'll see that Alice's ID in the AddressLookup table changes! It appears that this behavior is documented: An ON CONFLICT clause may be specified as part of an UPDATE or INSERT action within the body of the trigger. However if an ON CONFLICT clause is specified as part of the statement causing the trigger to fire, then conflict handling policy of the outer statement is used instead. So the "REPLACE" in the top-level "INSERT OR REPLACE" statement is overriding the critical "INSERT OR IGNORE" in the trigger program. Is there a way I can make it work the way that I wanted?

    Read the article

  • Image insertion from SQL info

    - by user528057
    What does 'howard.jpg' do in the sql statement below & how do I insert the image into my android app? CREATE TABLE IF NOT EXISTS employee ( _id INTEGER PRIMARY KEY AUTOINCREMENT, firstName VARCHAR(50), lastName VARCHAR(50), title VARCHAR(50), department VARCHAR(50), managerId INTEGER, city VARCHAR(50), officePhone VARCHAR(30), cellPhone VARCHAR(30), email VARCHAR(30), picture VARCHAR(200)) INSERT INTO employee VALUES(1,'Ryan','Howard','Vice President, North East', 'Management', NULL, 'Scranton','570-999-8888','570-999-8887','[email protected]','howard.jpg')

    Read the article

  • Adding a second table in a database

    - by MB
    Hi everyone. I used the code provided by the NoteExample from the developers doc to create a database. Now I want to add a second table to store different data. I simply "copied" the given code, but when I try to insert into the new table I get an error saying: "0ERROR/Database(370): android.database.sqlite.SQLiteException: no such table: routes: , while compiling: INSERT INTO routes(line, arrival, duration, start) VALUES(?, ?, ?, ?);" Can someone please take quick look at my DbAdapter class and give me a hint or a solution? I really don't see any problem. my code compiles without any errors.. thanks in advance! CODE: import static android.provider.BaseColumns._ID; 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; import android.util.Log; public class DbAdapter { public static final String KEY_FROM = "title"; public static final String KEY_TO = "body"; public static final String KEY_ROWID = "_id"; public static final String KEY_START = "start"; public static final String KEY_ARRIVAL = "arrival"; public static final String KEY_LINE = "line"; public static final String KEY_DURATION = "duration"; private static final String DATABASE_NAME = "data"; private static final String DATABASE_NOTESTABLE = "notes"; private static final String DATABASE_ROUTESTABLE = "routes"; private static final String TAG = "DbAdapter"; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; /** * Database creation sql statement */ private static final String DATABASE_CREATE_NOTES = "create table notes (_id integer primary key autoincrement, " + "title text not null, body text not null)"; private static final String DATABASE_CREATE_ROUTES = "create table routes (_id integer primary key autoincrement, " + "start text not null, arrival text not null, " + "line text not null, duration text not null);"; private static final int DATABASE_VERSION = 2; private final Context mCtx; 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_NOTES); Log.d(TAG, "created notes table"); db.execSQL(DATABASE_CREATE_ROUTES); //CREATE LOKALTABLE db.execSQL("CREATE TABLE " + DATABASE_ROUTESTABLE + " " + "(" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_START + " TEXT NOT NULL, " + KEY_ARRIVAL + " TEXT NOT NULL, " + KEY_LINE + " TEXT NOT NULL, " + KEY_DURATION + " TEXT NOT NULL"); Log.d(TAG, "created routes table"); } @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 DbAdapter(Context ctx) { this.mCtx = ctx; } /** * Open the notes database. If it cannot be opened, try to create a new * instance of the database. If it cannot be created, throw an exception to * signal the failure * * @return this (self reference, allowing this to be chained in an * initialization call) * @throws SQLException if the database could be neither opened or created */ public DbAdapter open() throws SQLException { mDbHelper = new DatabaseHelper(mCtx); mDb = mDbHelper.getWritableDatabase(); return this; } public void close() { mDbHelper.close(); } /** * Create a new note using the title and body provided. If the note is * successfully created return the new rowId for that note, otherwise return * a -1 to indicate failure. * * @param title the title of the note * @param body the body of the note * @return rowId or -1 if failed */ public long createNote(String title, String body) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_FROM, title); initialValues.put(KEY_TO, body); return mDb.insert(DATABASE_NOTESTABLE, null, initialValues); } /** * Create a new route using the title and body provided. If the route is * successfully created return the new rowId for that route, otherwise return * a -1 to indicate failure. * * @param start the start time of the route * @param arrival the arrival time of the route * @param line the line number of the route * @param duration the routes duration * @return rowId or -1 if failed */ public long createRoute(String start, String arrival, String line, String duration){ ContentValues initialValues = new ContentValues(); initialValues.put(KEY_START, start); initialValues.put(KEY_ARRIVAL, arrival); initialValues.put(KEY_LINE, line); initialValues.put(KEY_DURATION, duration); return mDb.insert(DATABASE_ROUTESTABLE, null, initialValues); } /** * Delete the note with the given rowId * * @param rowId id of note to delete * @return true if deleted, false otherwise */ public boolean deleteNote(long rowId) { return mDb.delete(DATABASE_NOTESTABLE, KEY_ROWID + "=" + rowId, null) > 0; } /** * Return a Cursor over the list of all notes in the database * * @return Cursor over all notes */ public Cursor fetchAllNotes() { return mDb.query(DATABASE_NOTESTABLE, new String[] {KEY_ROWID, KEY_FROM, KEY_TO}, null, null, null, null, null); } /** * Return a Cursor over the list of all routes in the database * * @return Cursor over all routes */ public Cursor fetchAllRoutes() { return mDb.query(DATABASE_ROUTESTABLE, new String[] {KEY_ROWID, KEY_START, KEY_ARRIVAL, KEY_LINE, KEY_DURATION}, null, null, null, null, null); } /** * Return a Cursor positioned at the note that matches the given rowId * * @param rowId id of note to retrieve * @return Cursor positioned to matching note, if found * @throws SQLException if note could not be found/retrieved */ public Cursor fetchNote(long rowId) throws SQLException { Cursor mCursor = mDb.query(true, DATABASE_NOTESTABLE, new String[] {KEY_ROWID, KEY_FROM, KEY_TO}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Return a Cursor positioned at the route that matches the given rowId * * @param rowId id of route to retrieve * @return Cursor positioned to matching route * @throws SQLException if note could not be found/retrieved */ public Cursor fetchRoute(long rowId) throws SQLException { Cursor mCursor = mDb.query(true, DATABASE_ROUTESTABLE, new String[] {KEY_ROWID, KEY_START, KEY_ARRIVAL, KEY_LINE, KEY_DURATION}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Update the note using the details provided. The note to be updated is * specified using the rowId, and it is altered to use the title and body * values passed in * * @param rowId id of note to update * @param title value to set note title to * @param body value to set note body to * @return true if the note was successfully updated, false otherwise */ public boolean updateNote(long rowId, String title, String body) { ContentValues args = new ContentValues(); args.put(KEY_FROM, title); args.put(KEY_TO, body); return mDb.update(DATABASE_NOTESTABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } }

    Read the article

  • SQLAlchemy - SQLite for testing and Postgresql for devlopment - How to port?

    - by StackUnderflow
    I want to use sqlite memory database for all my testing and Postgresql for my development/production server. But the SQL syntax is not same in both dbs. for ex: SQLite has autoincrement, and Postgresql has serial Is it easy to port the SQL script from sqlite to postgresql... what are your solutions? If you want me to use standard SQL, how should I go about generating primary key in both the databases?

    Read the article

  • How to insert a SQLite record with a datetime set to 'now' in Android application?

    - by droidguy
    Say, we have a table created as: create table notes (_id integer primary key autoincrement, created_date date) To insert a record, I'd use ContentValues initialValues = new ContentValues(); initialValues.put("date_created", ""); long rowId = mDb.insert(DATABASE_TABLE, null, initialValues); But how to set the date_created column to "now"? To make it clear, the initialValues.put("date_created", "datetime('now')"); Is not the right solution. It just sets the column to "datetime('now')" text.

    Read the article

  • How do I create a table in SQLite using the VS2008 Server Explorer

    - by fishhead
    Hello, I would like to create a table in a SQLite database using the Server Explorer in VS2008. I am able to do other operations on the database but when it comes to creating a table using the query builder I get Not Supported messages. is there another way other than writing code just for the sole purpose of creating the table? CREATE TABLE myTable ( ID INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR(100) ) .NET Framework Data Provider for SQLite 3.6.16

    Read the article

  • MySQL optimised code for 2 tables?

    - by David19801
    Hi, I have 2 tables, Table1: id,int1,int2,int3,int4,int5 Table2: integers (autoincrement),blobdata The query I want to use is given the id I want to get the blobdata from table2 associated with the 5 integers in table1. I've only ever used one table in mysql so have no idea how to do this properly. Is it possible? EDIT: id is username, integers in table2 is just integers. but have not built the tables yet, so can change if need to.

    Read the article

  • Change an autoincrementing field to one previous

    - by jlan
    One day, wordpress suddenly jumped from pots id 9110 to 890000000 post. Days later I'd like to move back new posts to continue from id 9111. I'm sure that id will never reach id 890000000, no problem here, but id is an autoincrement field and "ALTER TABLE wp8_posts AUTO_INCREMENT =9111" is not working. Can I force id to continue from 9111 ?

    Read the article

  • how to do multi insert and obtain ids

    - by liysd
    hi, I want to insert some data into a table (id PK autoincrement, val) with use multi insert INSERT INTO tab (val) VALUES (1), (2), (3) Is it possible to obtain a table of last inserted ids? I'm asking becouse I'm not sure if all will in this form: (n, n+1, n+2). I use mysql inodb.

    Read the article

  • Is possible overwriting a Doctrine model in Symfony?

    - by user248959
    Hi, is possible overwriting a Doctrine model in Symfony? I'm trying no change a "notnull" property, but i can get it.. In 'plugins/sfDoctrineGuardPlugin/config/doctrine/schema.yml': sfGuardUser: actAs: [Timestampable] columns: id: type: integer(4) primary: true autoincrement: true username: type: string(128) notnull: true unique: true #... And in 'config/doctrine/schema.yml': sfGuardUser: columns: username: type: string(128) notnull: false unique: true Then "build-all-reload" but it doesn't change.. Any idea? Javi

    Read the article

  • select records from table in the order in which i inserted

    - by echo
    consider a tale is as follows, EmployeeId | Name | Phone_Number Now, i insert 10 records... When i query them back, select * from myTable they are not selected in the order i inserted. I can obviously keep an autoincrement index and ORDER BY index. But i dont want to alter the table. How can i do this without altering the table?

    Read the article

  • Symfony: how would you reverse the "notnull:true" in a schema of a plugin?

    - by user248959
    Hi, sfGuardUser model of sfDoctrineGuardPlugin is defined this way: sfGuardUser: actAs: [Timestampable] columns: id: type: integer(4) primary: true autoincrement: true username: type: string(128) notnull: true unique: true As you can see 'username' has the feature "notnull:true". Now i want to create a register form that is not using 'username' but the email address of the user. When a user wants to register, it is showed this: Validation failed in class sfGuardUser 1 field had validation error: * 1 validator failed on username (notnull) Any idea? Javi

    Read the article

  • how to number the datas from mysql

    - by udaya
    Hi This is a doubt on mysql select query let me axplain my doubt with a simple example consider this is my query SELECT dbCountry from tableCountry tableCountry has fields dbCuntryId dbCountry and dbState I have the result as dbCountry india america england kenya pakisthan I need the result as 1 india 2 america 3 england 4 kenya 5 pakisthan the numbers 12345 must be generated with the increase in data and itis not a autoincrement id How can i get it is it something like loop

    Read the article

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