Issuing a sqilte query, picking a random result, and copying to the system clipboard

Tim Chase python.list at tim.thechases.com
Mon Jun 22 07:51:46 EDT 2015


On 2015-06-21 17:08, John T. Haggerty wrote:
> I'm looking to just have a simple program that will do a SQLite
> query pull a random record and then copy that record too the
> clipboard the system. I'm not quite seeing how to do this perhaps
> this is already been done elsewhere but I spent quite a bit of time
> trying to figure out how to do that and I'm not seeing a listing
> anywhere. any help would be greatly appreciated.

First, connect to your data source and obtain a cursor:

  import sqlite3
  conn = sqlite3.connect('file.sqlite')
  cur = conn.cursor()

then select a random row:

  cur.execute("SELECT * FROM table ORDER BY RANDOM() LIMIT 1")
  data = cur.fetchone()

then things get tricky because you don't specify what OS you have, as
there are plenty of occasions when there is no system clipboard.

On Win32, you'd need the Win32 add-on libraries to shove things onto
the clipboard, while under X, you'd need other facilities (either
using Tkinter or piping to something like xclip(1)), and yet another
way of doing things on MacOS.

-tkc







More information about the Python-list mailing list