Skip to content

Instantly share code, notes, and snippets.

@yokawasa
Created April 25, 2018 01:01
Show Gist options
  • Save yokawasa/0e8e9479b8dec40fad1eaf8c3ac80808 to your computer and use it in GitHub Desktop.
Save yokawasa/0e8e9479b8dec40fad1eaf8c3ac80808 to your computer and use it in GitHub Desktop.
Sample Python application that reads MySQL configurations from ENV and executes simple operations
import MySQLdb as db
import os
# MySQL configurations
MYSQL_USER = os.environ['MYSQL_USER']
MYSQL_PASSWORD = os.environ['MYSQL_PASSWORD']
MYSQL_HOST = os.environ['MYSQL_HOST']
MYSQL_DATABASE = os.environ['MYSQL_DATABASE']
print(MYSQL_USER)
print(MYSQL_PASSWORD)
print(MYSQL_HOST)
print(MYSQL_DATABASE)
def main():
conn = db.connect(
user=MYSQL_USER,
passwd=MYSQL_PASSWORD,
host=MYSQL_HOST,
db=MYSQL_DATABASE
)
c = conn.cursor()
sql = 'drop table if exists test'
c.execute(sql)
sql = 'create table test (id int, content varchar(32))'
c.execute(sql)
sql = 'show tables'
c.execute(sql)
print('===== table list =====')
print(c.fetchone())
# insert records
sql = 'insert into test values (%s, %s)'
c.execute(sql, (1, 'hoge'))
datas = [
(2, 'foo'),
(3, 'bar')
]
c.executemany(sql, datas)
# select records
sql = 'select * from test'
c.execute(sql)
print('===== Records =====')
for row in c.fetchall():
print('Id:', row[0], 'Content:', row[1])
conn.commit()
c.close()
conn.close()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment