Data files · databases
SQL Connect: Opening a Database Connection from a Script
An SQL connect step links a script to a database server so that queries can be sent and rows returned. The idea is the same whether the server runs on the same machine or across a network: the script supplies a few facts about where the database lives and who is asking, receives a connection object in return, and uses that object for every later operation. This page explains the pieces of a connection, the habits that keep it safe, and the path from a result set to a matrix. It is part of the collection under Data and files.
What a connection needs
Five items identify a connection to most database servers: the host name or address, the port, the database name, the user name, and the password. Some systems wrap these in a single connection string of key-value pairs, and some use a file path instead, as with an embedded database where the whole database is one file. A driver, the library that speaks the server’s protocol, sits underneath. Without the right driver installed the connect call fails before it reaches the network, and that error message is often the first thing a newcomer sees.
Keep credentials out of the script text. Read the password from an environment variable or a protected configuration file, so that the script can be shared or stored in version control without exposing it. Give the account only the rights the script needs; a reporting script that reads data should connect as a read-only user.
import os, sqlite3 # sqlite3 stands in for any driver
conn = sqlite3.connect("measurements.db") # a file-based database
cur = conn.cursor()
cur.execute("SELECT t, value FROM readings WHERE run = ?", (7,))
rows = cur.fetchall()
conn.close()
With a networked server the call takes the host, port and credentials instead of a file name, but the shape of the code does not change.
Parameters, not string pasting
The question mark in the snippet is a placeholder, and the value 7 travels separately. Building the query by pasting text together invites two problems: quotes inside the data break the statement, and hostile input can change its meaning. Parameterized queries remove both. Whenever a value comes from a file, a user, or another system, it belongs in a parameter.
Opening, using, closing
A connection holds resources on both ends, and servers limit how many they accept. Open one, do the work, and close it, ideally inside a construct that closes it even if an error occurs; the pattern is described under trapping errors in scripts. For many short queries, reuse one connection instead of opening a new one each time, because the handshake costs far more than a small query.
Writes need one more step. Changes made through a connection are usually held in a transaction until a commit is issued, and an error before the commit rolls them back. That is the right behavior for a script that inserts a thousand rows and should leave nothing behind if the thousand-and-first fails.
From result set to matrix
A query returns rows of fields. If every selected column is numeric, converting to a matrix is direct: the number of records becomes the number of rows, and the number of selected columns becomes the number of columns. A query returning 250 records with 3 numeric columns gives a 250 × 3 matrix.
import numpy as np
A = np.array(rows, dtype=float) # NULL arrives as None, which fails here
Database NULL values arrive as a special none value and break the float conversion. Either filter them out in the query, replace them there with a default, or convert them to NaN in the script and decide later how to treat them. Sort in the query with an ORDER BY clause, since a result set has no guaranteed order otherwise.
Text columns need separate handling; pull them into lists and keep them apart from the numeric block. When the data arrives from a file instead of a server, see reading spreadsheet files into a matrix, and for type conversions on individual fields, see ASCII to double conversion.