SQLite: How to get the row ID after inserting a row into a table

February 1st, 2013

When working with SQL databases it can often be useful to keep a record of the ID of the row in a table from which a piece of data was read. For example, if you have a Customers table in a database then if you populate a list of Customer objects in your application from the rows in the table, storing the row ID for each object lets you easily update the correct row if you edit the values in one of the Customer objects.

In SQLite, if you have a field of type INTEGER PRIMARY KEY in a table, the database engine will automatically fill the field with the ID for the row. When you insert a new row in the table, e.g. add a new customer into the Customers table taking the example above, then you will need to find out the ID of the new row so you can write it back into the Customer object you’ve just added.

SQLite has a special SQL function – last_row_id() – that returns the ID of the last row inserted into the database so getting the ID of a new row after performing a SQL insert just involves executing the last_row_id() command.

Here is an example in C# showing how to get the ID of the last row inserted into a table in a database.

Create the SQLite database and open a connection to it:

 String mPathName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "testdba.db3");


 // Open a connection to the database.
 SQLiteConnection Conn = new SQLiteConnection("Data Source = " + mPathName);


Create a table (Customers) in the SQLite database:

 // Create a table.

 SQLiteCommand Command = new SQLiteCommand(SQL, Conn);

 // Create the table.

Insert a row of data into the table:

 // Reuse the command object and insert a row into the table.

 Command.CommandType = System.Data.CommandType.Text;

 Command.Parameters.Add(new SQLiteParameter("@UNIQUEID", "Fred Bloggs"));
 Command.Parameters.Add(new SQLiteParameter("@ADDRESS", "Acacia Avenue"));

 int Status = Command.ExecuteNonQuery();

Now get the ID of the last row inserted:

 Command.CommandText = "select last_insert_rowid()";

 // The row ID is a 64-bit value - cast the Command result to an Int64.
 Int64 LastRowID64 = (Int64)Command.ExecuteScalar();

 // Then grab the bottom 32-bits as the unique ID of the row.
 int LastRowID = (int)LastRowID64;

Note that in SQLite the row ID is a 64-bit integer but for all practical database sizes you can cast the 64 bit value to a 32-bit integer.

For more SQLite database tips check out:


SQLite: How to Determine if a Column Exists in a Table

January 20th, 2013

As part of developing a new application using the SQLite database I need to perform some standard database checks when the application starts. Firstly I need to check that the application’s database exists and then either create the database if it doesn’t exist, or, if the database does exist, check that the tables in the SQLite database contain the columns expected by the app.

Checking whether the Database Exists

Checking that the SQLite database exists is easy, I can simply use code like:

if (!File.Exists(mPathName))

i.e. I can use the normal System.IO methods in .Net to check whether the database is present.

Creating a SQLite Database

Creating a SQLite database is also straightforward in SQLite. I can create the database file as follows:

// Create the database file.

// Open a connection to the database.
using (SQLiteConnection Conn = new SQLiteConnection("Data Source = " + mPathName))

    // Create the required tables. In this example, I'm creating a Customers table with 3 fields - ID, UNIQUEID and DATAFIELD.

    using (SQLiteCommand Command = new SQLiteCommand(SQL, Conn))


This is all pretty standard SQL and ADO.Net.

Checking if Columns Exist in the SQLite Database

Checking whether columns exist was a little harder to work out for SQLite. Some other databases I’ve used has special methods to get the tables, columns and their attributes. SQLite didn’t have a class to enable me to do this quite so obviously but after some research and experimentation, I found the following code worked:

// Open a connection to the database.
using (SQLiteConnection Conn = new SQLiteConnection("Data Source = " + mPathName))

    // Get the schema for the columns in the database.
    DataTable ColsTable = Conn.GetSchema("Columns");

    // Query the columns schema using SQL statements to work out if the required columns exist.
    bool IDExists       = ColsTable.Select("COLUMN_NAME='ID' AND TABLE_NAME='Customers'").Length != 0;
    bool UNIQUEIDExists = ColsTable.Select("COLUMN_NAME='UNIQUEID' AND TABLE_NAME='Customers'").Length != 0;
    bool ElephantExists = ColsTable.Select("COLUMN_NAME='ELEPHANT' AND TABLE_NAME='Customers'").Length != 0;


A statement like

ColsTable.Select("COLUMN_NAME='ID' AND TABLE_NAME='Customers'")

returns an array of DataRows. If the column doesn’t exist an array of length 0 will be returned, hence the .Length != 0 check.

Adding a Column if it doesn’t Exist in the SQLite Database

Adding a column to a SQLite database can be performed using standard SQL statements.


using (SQLiteCommand Command = new SQLiteCommand(SQL, Conn))

It turns out that performing these basic operations on a SQLite database is pretty straightforward when you know how. One thing I haven’t bothered to find out yet is to determine whether a column has the correct attributes, e.g. my example ELEPHANT column may change from a 100 character to a 200 character wide column between different versions of the application. However, I’ve never had a good reason for doing such a database update in the past. I’m also relying on the SQLite feature where the database will store any sort of data of almost any length in any column.

For more SQLite tips, see:


Human-Centered Design – An Introduction to Designing for Ease of Use

January 18th, 2013

Designing products that are easy to use is not a simple exercise. After a number of years spent designing a range of PC and industrial products, my experience is that those products which appear the simplest, cleanest and easiest to use are, more often than not, the ones that took the most amount of effort to design and complete. Constructing a product that simply exposes every possible feature at once to the user is relatively easy. What’s more difficult is prioritising the user interface, making the most frequent and essential elements readily available while pushing the more advanced, less frequently used features into the background.


One of the biggest obstacles to overcome when beginning to design anything that is easy to use is the designer’s ego. Almost all designers, whatever their field, e.g.  software, mechanical, usually hold some sort of innate belief about what the user wants and what the best solution should be. This is a natural and essential requirement for any designer. Without the self-belief and initiative to construct a solution a designer would not be able to form an innovative solution for a user need. However, in any mature development process, the ultimate design of a product should not be allowed to rely on what may turn out to be a prejudice, personal desire or pet theory of the loudest or most assertive engineer (or manager) on the team.

One process that can be adopted in any development program is Human-Centred or User-Centred Design. For a process that has sounds rather complicated, it’s actually based on some very simple and low-tech ideas. To describe HCD, let’s break the development process into 3 distinct stages:-

1. Understand the user’s requirements for the product.

In particular try to gain an understanding of the user’s pain point or difficulties.

2. Innovate and design a solution for the user’s product requirements.

3. Test and evaluate the solution with users.

Take the lessons learned and go back to stage 1.

Repeat steps 1, 2 and 3 as required. Any development is a compromise and engineering judgement needs to be used to decide when the improvements are no longer worth the effort of repeating the cycle. HCD techniques come into play mainly in stages 2 and 3 giving the solution developers a set of techniques for presenting and evaluating solutions with users as well as techniques for prioritising evaluation results.

I opened this post by saying that designing for ease of use is not a simple exercise. Although there are only 3 steps listed above they all involve a lot of work, usually over a significant period of time. Adopting HCD techniques can help you increase the chances of a successful development. I’ll elaborate on the HCD techniques in a follow-up post.

Apple Mac: How to Take a Screenshot

January 13th, 2013

One nifty feature I’ve found with my new Apple Mac Mini is that taking screenshots is real easy. If you want to capture an image of a portion of the desktop, simply type the key sequence:


i.e. press down both the cmd key and the shift key then press the 4 key at the same time.

The Mac then displays cursors that you can drag with the mouse to grab any portion of the screen you like – press the left mouse button to begin capture then move the mouse to encompass the desired are before releasing the left mouse button to complete the capture. The image is then automatically saved as a PNG file on the desktop.

After the image is saved onto the desktop, double-clicking the image with the mouse displays the image in the Preview tool. The Preview tool contains a number of handy features, e.g. the Tools menu lets you resize the image and the File menu contains options to export the image in different formats, e.g. as a .JPG file.

Apple Mac: Enabling the Mouse Right-Click

January 13th, 2013

Having recently bought an Apple Mac, I’d begun working my way through tutorials on how to use XCode, Apple’s IDE for iPhone/ iPad development. Coming from a PC, I had a learning curve on how to use some of the basic Mac features. I’m not saying the Mac is better or worse than a PC, just different. It’s always good to learn something new!

One thing that did confuse me for a while was that the tutorials I was following required me to right-click the mouse on certain items to bring up a context menu. Unfortunately this simply didn’t work, I clicked on the right side of the mouse but no menu appeared. My confusion was increased as the mouse I’d bought (for over £30!) didn’t appear to have separate left and right buttons. Eventually I figured out that the mouse was configurable and that I had to enable use of the right mouse button feature as it wasn’t enabled by default. To enable the right mouse, I had to open the System Preferences by clicking on this button:

Apple-Mac-System-Preferencesthen navigate to the Mouse preferences under the Hardware section in the preferences. Finally I had to enable the Secondary button for the right mouse button as shown in this picture:


After doing this, I could right-click the mouse and bring up the context menu, just like on a PC.

Hands Up Who Likes Business Planning?

November 20th, 2012


Do you find you don’t have time to do any business planning?  Are you too busy getting on with the actual business side of things, the things that get the income coming in? Or perhaps more honestly, you think that “planning” or “strategy” is:-

a) boring as heck?
b) a mystery?
c) irrelevant?

So What Is Business Planning?


Well there’s the start-up business plan which is your tool for setting out your initial goals and how you will achieve them. It takes a detailed look at your proposed business idea and how likely it is to succeed. It includes financial forecasts covering what money you see coming in and going out of your business. It usually covers a 3-5 year period. This video explains more about it – https://www.gov.uk/write-business-plan


You’d be forgiven for thinking that “business planning” was only something to do when starting up rather than running a business. If you google “business planning” for example, a high proportion of articles will be about start-ups and creating you first  business plan.
But once you’re in business, it pays to refer back regularly to your original plan to see whether things are going according to plan, financially and in relation to your other goals.

If you aware that things are not going to plan, you can do what is necessary to address any issues before they become critical. Also unexpected changes can be positive developments. You may find a market for your audience that you hadn’t been aware of before. If you take the time to look at how these changes fit in with your overall goals, it will help you keep focussed.
In addition to regular monitoring of your cashflow, you might once a year, review your goals & make plans in the areas of finance, sales, marketing, HR, for example.

Setting measurable objectives for the year ahead makes it easier to monitor your performance. So rather than vague goals such as “increase sales” or “raise company profile” set specific and realistic targets such as % increase in sales, 3 articles in local paper, x number of facebook fans, reduce overdraft by x amount.

I’ve talked to several people who run small businesses over the years and I’m always amazed that planning is often so far down on their agenda or sometimes not on their radar at all!

If you applied that logic elsewhere it would seem a bit odd. For example, you don’t step out of your front door in the morning without an idea of where it is you’re going.

A while back I was working as Communications Officer for an organisation and had been asked to produce a Communications Strategy. I was talking to my boss one day about the importance of strategy and said “if you don’t have a strategy, you’re in the dark, a bit like trying to pack for a holiday without knowing where you’re going “. He said “Oh! I’d happily go with an empty suitcase!”.
That taught me a valuable lesson. To remember that not everyone has the same outlook on life, the same values or personality. Luckily for me, I like planning, I’m more of thinker than do-er, so it’s not a chore for me to spend time analysing and committing ideas to paper. But if you’re a do-er I can quite understand that you may well prefer to watch paint dry than sit down and write business forecasts.

If for whatever reason, you find yourself saying “no” to the task of business planning, at least be aware of how vulnerable that makes your business.  Lack of planning is often cited as one of the reasons for small business failure.  There’s plenty of guidance on planning out there. Here are a few sources of information to start you off:


For further business tips, check out our blog post on simple accounting tips.

Windows 8 Tablets – Two Tablets for Different Users?

November 18th, 2012

Tablet computers like the iPad are extremely convenient for mobile use, e.g. sending emails or browsing the internet. However they aren’t so handy for performing the kinds of task you might use a PC for, e.g. using Word or Excel. Personally, I love the iPad for browsing the internet but for data entry, e.g. using an application like Word or Excel, or even simple actions like copying and pasting text between web pages I much prefer using a PC.

Recently, Microsoft have released Windows 8 and at the same time a new Windows 8 tablet – the Microsoft Surface RT. At first glance the Microsoft RT seems like an ideal mix – a handy, touch-sensitive tablet like the iPad that will also run your familiar applications like Word, Excel (or even our own SliQTools applications :)). However, bear in mind that there is more than one form of the new tablet and you should make sure you are buying the correct version.


Microsoft Surface RT – an iPad-like device

The current release of the Surface is the Microsoft Surface RT.

The first thing to know is that the current Microsoft Surface – the Microsoft Surface RT – will NOT run the normal desktop applications you can run on Windows 7. The Surface RT is much more like an iPad than a laptop computer running Windows 7 and the Surface RT will only run the new tablet-like Windows Apps, purchased from the new Microsoft Windows Store. The new Windows 8 Apps are more like iPad apps than the normal programs we’ve all been running on Windows 7.

The exception to the “does not run old application rule” for the Surface RT is that it does comes preloaded with a special version of Microsoft Office 2013 specifically designed for the RT so you can work with your older Word and Excel documents on the new RT.

Microsoft Surface Pro – Laptop PC + iPad-like device in one

In the new year, Microsoft will release the Microsoft Surface Pro. This is the killer machine in my view. It will work like an iPad, with a touch-sensitive screen, run the new Windows 8 Apps from the Microsoft Windows store, but also run ALL your old programs that you were using on Windows 7, Vista, XP etc. The Surface Pro will cost more than an iPad but will double up as a laptop with a proper keyboard and mouse pad for effective data entry.

One clear area where the new Surface machines win out on over the iPad or Android tablets is in connectivity. The Surface machines come with USB ports,  microSD card slot, headphone, micro-HDMI, keyboard dock and charging ports as well as an in-built camera.


Information on the new Microsoft Surface and Windows 8 releases can be confusing. Make sure you know what you want to do with the Surface and that you are choosing the right version when you buy. Personally, I’m waiting for the Surface Pro to be released as the ability to browse the internet conveniently as I can with my iPad but also run my normal desktop apps means I’ll get the best of both worlds in terms of portability and flexibility.

For more Windows 8 topics, see http://www.sliqtools.co.uk/blog/windows-help/windows-8-how-to-set-live-mail-as-the-default-email-client/ and http://www.sliqtools.co.uk/blog/general/how-to-turn-off-a-windows-8-pc/.

Windows 8 – How to set Live Mail as the Default Email Client

November 8th, 2012

Some time ago I wrote a blog post about how to set Windows Live Mail as the default email client on Windows 7. Windows Live Mail is still present on Windows 8 but the procedure for setting it as the default program for sending mail via programs like SliQ Invoicing is different as Windows 8 has a new start menu. Here’s how to set Live Mail as the default:

Note: If you follow the instructions below and can’t find Windows Live Mail in the list of programs, read this blog post on how to download and install Windows Live Mail as part of Microsoft’s free Windows Essentials.

1. If you are in desktop mode in Windows 8, press the Windows key on your keyboard (which will switch Windows 8 to show the Start menu).

2. Then just start typing the word “default programs”. The Start menu will then list programs matching the text you are typing and should show the Default Programs app on the top left of the screen as follows:


3. Click on the Default Programs App.

Windows will then switch to desktop mode and show the Set Default Programs window.


4. Make sure Windows Live Mail is selected in the list on the left and click the Set this program as default button (highlighted in the picture above).

Windows Live Mail should now be your default email program, so if you click on a file in Windows Explorer and right-click then email it, Windows Live Mail should be launched automatically.

For more email troubleshooting advice with SliQ Invoicing Plus, see http://www.sliqtools.co.uk/troubleshooting-email-problems.aspx

How to turn off a Windows 8 PC

November 1st, 2012

With Windows 7 or Vista, turning off a PC is simply a matter of clicking the Windows button on the left of the task bar and clicking the Shutdown button. Having just installed Windows 8, it took me a while to work out how to turn the PC off as there is no longer a Windows button and the Start menu is completely different. Here’s how to do it:

1. Bring up the Windows 8 Charms buttons (a strip of buttons arranged down the right of the screen) by moving your mouse cursor the very top right of the screen.

2. Click the Settings charm button.

3. In the Settings, click the Power button:


Problems running .Net 2.0 programs on Windows 8

November 1st, 2012

Unlike Windows 7,  a Windows 8 install does not always include .Net 3.X and .Net 2.X versions. I’ve upgraded a Windows 7 PC which already had the older versions of the .Net frameworks installed and the frameworks were preserved in Windows 8 but on a fresh install to a PC only .Net 4.5 was included.

Since .Net 2.0 is not always present on Windows 8, this makes it difficult to know whether older programs will run successfully. It turns out that support for .Net 2.0 and 3.5 is an optional part of Windows 8. Quite why they’re optional I don’t know. However, if you are trying to run an older program on Windows 8 and as soon as you try to run it, Windows says “XXX has stopped working”, the first thing I’d recommend checking is whether .Net 2.0 and 3.5 are included.

With earlier versions of Windows, you’d have to manually download and install the frameworks but Windows 8 includes a neat way of adding features like the .Net framework. For those unfamiliar with Windows 8 (which included me), finding the features dialog took some searching. Here’s how to find the dialog and turn on support for the older .Net 2.0 and .Net 3.5 frameworks:

1. Show the Windows 8 charms (a set of buttons down the right hand edge of the screen), by moving your mouse cursor into the very top right corner of the screen as shown in the following picture:


I must say this way of bringing up the charms didn’t feel very intuitive, especially as I had to move the mouse right to the very top of the screen rather than just to the right where the actual charms buttons appear.

2. Press the Search charm button to bring up the Search panel. Then click on the Settings button and type in Windows Features to the search box:


Windows will then show the Settings items matching “windows Features” on the left of the screen.

3. Click on the Turn Windows Features On and Off button:


Windows will then show the Windows Features dialog.

4. In the Windows Features dialog, make sure that the .Net Framework 3.5 (includes .Net 2.0 and 3.0) option is checked:


5. Then click OK.

Windows 8 will then install the required files. At the end of the install, a reboot may be required. After the reboot, older programs needing .Net 2.0 or 3.0 etc. should run OK.