Skip to content

Instantly share code, notes, and snippets.

@kcsaff
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kcsaff/949576bb34a375a0c404 to your computer and use it in GitHub Desktop.
Save kcsaff/949576bb34a375a0c404 to your computer and use it in GitHub Desktop.
Simple one-file solution to ease using MySQL databases from the command line.
"""
This is a short library to help connecting to a MySQL database from the command line.
You'll need MySQLdb (or its fork, mysql-client) to use this.
"""
from getpass import getpass
try:
import MySQLdb
except ImportError as e:
print(e)
MySQLdb = None
def parse_connection(conn):
"""
Parse a connection string of the form [user@]host[:port][/db], where all but the host section are optional.
>>> from pprint import pprint
>>> pprint(parse_connection('george:curious@yellow.hat/man'), width=100, compact=True)
{'db': 'man', 'host': 'yellow.hat', 'passwd': 'curious', 'port': None, 'user': 'george'}
"""
if '@' in conn:
user, conn = conn.split('@', 1)
else:
user = None
if user and ':' in user:
user, passwd = user.rsplit(':', 1)
else:
passwd = None
if '/' in conn:
conn, db = conn.rsplit('/', 1)
else:
db = None
if ':' in conn:
conn, port = conn.rsplit(':', 1)
else:
port = None
host = conn
return dict(host=host, port=port, db=db, user=user, passwd=passwd)
def query_connection(host=None, port=None, db=None, user=None, passwd=None):
"""Get all necessary, but absent, database connection parameters from the user.
"""
if set(host) & set('@:/'):
return query_connection(**parse_connection(host))
if host is None:
host = input('Host IP or domain for MySQL server?')
if port is None:
port = 3306
else:
port = int(port)
if db is None:
db = input('Which database at {host} to use?'.format(host=host))
if user is None:
user = input('Username for {host}:{port}?'.format(host=host, port=port))
if passwd is None:
passwd = getpass('Password for {user}@{host}:{port}/{db}? '.format(host=host, port=port, user=user, db=db))
return dict(host=host, port=port, db=db, user=user, passwd=passwd)
def connect_mysql(host=None, port=None, db=None, user=None, passwd=None):
"""
Returns a MySQL connection using the provided connection parameters.
If any required parameters aren't given, the user will be asked to enter it.
"""
verify_mysqldb(True)
if None in (host, port, db, user, passwd):
return connect_mysql(**query_connection(host, port, db, user, passwd))
return MySQLdb.connect(host=host, port=port, user=user, passwd=passwd, db=db)
def verify_mysqldb(reimport=False):
if not MySQLdb:
import sys
print("WARNING: The library MySQLdb is not available to this python instance `{0}` -- this script will not function."
.format(sys.executable)
)
if reimport:
import MySQLdb as MySQLdbReimport
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment