Fixes all functions except CSV for time period.

This commit is contained in:
Patrick McDonagh
2016-11-01 16:56:22 -05:00
parent 72f1cb6684
commit 849b4e5d82
859 changed files with 54963 additions and 178925 deletions

View File

@@ -0,0 +1,123 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
Example using MySQL Connector/Python showing:
* How to get datetime, date and time types
* Shows also invalid dates returned and handled
* Force sql_mode to be not set for the active session
"""
from datetime import datetime
import mysql.connector
# Note that by default MySQL takes invalid timestamps. This is for
# backward compatibility. As of 5.0, use sql modes NO_ZERO_IN_DATE,NO_ZERO_DATE
# to prevent this.
_adate = datetime(1977, 6, 14, 21, 10, 00)
DATA = [
(_adate.date(), _adate, _adate.time()),
('0000-00-00', '0000-00-00 00:00:00', '00:00:00'),
('1000-00-00', '9999-00-00 00:00:00', '00:00:00'),
]
def main(config):
output = []
db = mysql.connector.Connect(**config)
cursor = db.cursor()
tbl = 'myconnpy_dates'
cursor.execute('SET sql_mode = ""')
# Drop table if exists, and create it new
stmt_drop = "DROP TABLE IF EXISTS {0}".format(tbl)
cursor.execute(stmt_drop)
stmt_create = (
"CREATE TABLE {0} ( "
" `id` tinyint(4) NOT NULL AUTO_INCREMENT, "
" `c1` date DEFAULT NULL, "
" `c2` datetime NOT NULL, "
" `c3` time DEFAULT NULL, "
" `changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP "
" ON UPDATE CURRENT_TIMESTAMP, "
"PRIMARY KEY (`id`))"
).format(tbl)
cursor.execute(stmt_create)
# not using executemany to handle errors better
stmt_insert = ("INSERT INTO {0} (c1,c2,c3) VALUES "
"(%s,%s,%s)".format(tbl))
for data in DATA:
try:
cursor.execute(stmt_insert, data)
except (mysql.connector.errors.Error, TypeError) as exc:
output.append("Failed inserting {0}\nError: {1}\n".format(
data, exc))
raise
# Read the names again and print them
stmt_select = "SELECT * FROM {0} ORDER BY id".format(tbl)
cursor.execute(stmt_select)
for row in cursor.fetchall():
output.append("%3s | %10s | %19s | %8s |" % (
row[0],
row[1],
row[2],
row[3],
))
# Cleaning up, dropping the table again
cursor.execute(stmt_drop)
cursor.close()
db.close()
return output
if __name__ == '__main__':
#
# Configure MySQL login and database to use in config.py
#
config = {
'host': 'localhost',
'port': 3306,
'database': 'test',
'user': 'root',
'password': '',
'charset': 'utf8',
'use_unicode': True,
'get_warnings': True,
}
out = main(config)
print('\n'.join(out))

View File

@@ -0,0 +1,68 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
Example using MySQL Connector/Python showing:
* that show engines works..
"""
import sys, os
import mysql.connector
def main(config):
output = []
db = mysql.connector.Connect(**config)
cursor = db.cursor()
# Select it again and show it
stmt_select = "SHOW ENGINES"
cursor.execute(stmt_select)
rows = cursor.fetchall()
for row in rows:
output.append(repr(row))
db.close()
return output
if __name__ == '__main__':
config = {
'host': 'localhost',
'port': 3306,
'database': 'test',
'user': 'root',
'password': '',
'charset': 'utf8',
'use_unicode': True,
'get_warnings': True,
}
out = main(config)
print('\n'.join(out))

View File

@@ -0,0 +1,95 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
Example using MySQL Connector/Python showing:
* dropping and creating a table
* inserting 3 rows using executemany()
* selecting data and showing it
"""
import mysql.connector
def main(config):
output = []
cnx = mysql.connector.connect(**config)
cur = cnx.cursor()
# Drop table if exists, and create it new
stmt_drop = "DROP TABLE IF EXISTS names"
cur.execute(stmt_drop)
stmt_create = (
"CREATE TABLE names ("
" id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, "
" name VARCHAR(30) DEFAULT '' NOT NULL, "
" info TEXT DEFAULT '', "
" age TINYINT UNSIGNED DEFAULT '30', "
"PRIMARY KEY (id))"
)
cur.execute(stmt_create)
info = "abc" * 10000
# Insert 3 records
names = (('Geert', info, 30), ('Jan', info, 31), ('Michel', info, 32))
stmt_insert = "INSERT INTO names (name, info, age) VALUES (%s, %s, %s)"
cur.executemany(stmt_insert, names)
cnx.commit()
# Read the names again and print them
stmt_select = "SELECT id, name, info, age FROM names ORDER BY id"
cur.execute(stmt_select)
for row in cur.fetchall():
output.append("%d | %s | %d\nInfo: %s..\n" % (
row[0], row[1], row[3], row[2][:20]))
# Cleaning up, dropping the table again
cur.execute(stmt_drop)
cur.close()
cnx.close()
return output
if __name__ == '__main__':
config = {
'host': 'localhost',
'port': 3306,
'database': 'test',
'user': 'root',
'password': '',
'charset': 'utf8',
'use_unicode': True,
'get_warnings': True,
}
out = main(config)
print('\n'.join(out))

View File

@@ -0,0 +1,119 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
Example using MySQL Connector/Python showing:
* How to save timestamps including microseconds
* Check the MySQL server version
NOTE: This only works with MySQL 5.6.4 or greater. This example will work
with earlier versions, but the microseconds information will be lost.
Story: We keep track of swimmers in a freestyle 4x 100m relay swimming event
with millisecond precision.
"""
from datetime import time, datetime
import mysql.connector
CREATE_TABLE = (
"CREATE TABLE relay_laps ("
"teamid TINYINT UNSIGNED NOT NULL, "
"swimmer TINYINT UNSIGNED NOT NULL, "
"lap TIME(3), "
"start_shot DATETIME(6), "
"PRIMARY KEY (teamid, swimmer)"
") ENGINE=InnoDB"
)
def main(config):
output = []
cnx = mysql.connector.Connect(**config)
if cnx.get_server_version() < (5,6,4):
output.append(
"MySQL {0} does not support fractional precision"\
" for timestamps.".format(cnx.get_server_info()))
return output
cursor = cnx.cursor()
try:
cursor.execute("DROP TABLE IF EXISTS relay_laps")
except:
# Ignoring the fact that it was not there
pass
cursor.execute(CREATE_TABLE)
teams = {}
teams[1] = [
(1, time(second=47, microsecond=510000),
datetime(2009, 6, 7, 9, 15, 2, 234)),
(2, time(second=47, microsecond=20000),
datetime(2009, 6, 7, 9, 30, 5, 102345)),
(3, time(second=47, microsecond=650000),
datetime(2009, 6, 7, 9, 50, 23, 2300)),
(4, time(second=46, microsecond=60000),
datetime(2009, 6, 7, 10, 30, 56, 1)),
]
insert = ("INSERT INTO relay_laps (teamid, swimmer, lap, start_shot) "
"VALUES (%s, %s, %s, %s)")
for team, swimmers in teams.items():
for swimmer in swimmers:
cursor.execute(insert, (team, swimmer[0], swimmer[1], swimmer[2]))
cnx.commit()
cursor.execute("SELECT * FROM relay_laps")
for row in cursor:
output.append("{0: 2d} | {1: 2d} | {2} | {3}".format(*row))
try:
cursor.execute("DROP TABLE IF EXISTS relay_lapss")
except:
# Ignoring the fact that it was not there
pass
cursor.close()
cnx.close()
return output
if __name__ == '__main__':
config = {
'host': 'localhost',
'port': 3306,
'database': 'test',
'user': 'root',
'password': '',
'charset': 'utf8',
'use_unicode': True,
'get_warnings': True,
}
out = main(config)
print('\n'.join(out))

View File

@@ -0,0 +1,100 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
Example using MySQL Connector/Python showing:
* sending multiple statements and iterating over the results
"""
import mysql.connector
def main(config):
output = []
db = mysql.connector.Connect(**config)
cursor = db.cursor()
# Drop table if exists, and create it new
stmt_drop = "DROP TABLE IF EXISTS names"
cursor.execute(stmt_drop)
stmt_create = (
"CREATE TABLE names ("
" id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, "
" name VARCHAR(30) DEFAULT '' NOT NULL, "
" info TEXT DEFAULT '', "
" age TINYINT UNSIGNED DEFAULT '30', "
" PRIMARY KEY (id))"
)
cursor.execute(stmt_create)
info = "abc" * 10000
stmts = [
"INSERT INTO names (name) VALUES ('Geert')",
"SELECT COUNT(*) AS cnt FROM names",
"INSERT INTO names (name) VALUES ('Jan'),('Michel')",
"SELECT name FROM names",
]
# Note 'multi=True' when calling cursor.execute()
for result in cursor.execute(' ; '.join(stmts), multi=True):
if result.with_rows:
if result.statement == stmts[3]:
output.append("Names in table: " +
' '.join([name[0] for name in result]))
else:
output.append(
"Number of rows: {0}".format(result.fetchone()[0]))
else:
output.append("Inserted {0} row{1}".format(
result.rowcount,
's' if result.rowcount > 1 else ''))
cursor.execute(stmt_drop)
cursor.close()
db.close()
return output
if __name__ == '__main__':
config = {
'host': 'localhost',
'port': 3306,
'database': 'test',
'user': 'root',
'password': '',
'charset': 'utf8',
'use_unicode': True,
'get_warnings': True,
}
out = main(config)
print('\n'.join(out))

View File

@@ -0,0 +1,77 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
Example using MySQL Connector/Python showing:
* using warnings
"""
import mysql.connector
STMT = "SELECT 'abc'+1"
def main(config):
output = []
config['get_warnings'] = True
db = mysql.connector.Connect(**config)
cursor = db.cursor()
db.sql_mode = ''
output.append("Executing '%s'" % STMT)
cursor.execute(STMT)
cursor.fetchall()
warnings = cursor.fetchwarnings()
if warnings:
for w in warnings:
output.append("%d: %s" % (w[1],w[2]))
else:
output.append("We should have got warnings.")
raise Exception("Got no warnings")
cursor.close()
db.close()
return output
if __name__ == '__main__':
config = {
'host': 'localhost',
'port': 3306,
'database': 'test',
'user': 'root',
'password': '',
'charset': 'utf8',
'use_unicode': True,
'get_warnings': True,
}
out = main(config)
print('\n'.join(out))

View File

@@ -0,0 +1,97 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""Example using MySQL Prepared Statements
Example using MySQL Connector/Python showing:
* usage of Prepared Statements
"""
import mysql.connector
from mysql.connector.cursor import MySQLCursorPrepared
def main(config):
output = []
cnx = mysql.connector.Connect(**config)
curprep = cnx.cursor(cursor_class=MySQLCursorPrepared)
cur = cnx.cursor()
# Drop table if exists, and create it new
stmt_drop = "DROP TABLE IF EXISTS names"
cur.execute(stmt_drop)
stmt_create = (
"CREATE TABLE names ("
"id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, "
"name VARCHAR(30) DEFAULT '' NOT NULL, "
"cnt TINYINT UNSIGNED DEFAULT 0, "
"PRIMARY KEY (id))"
)
cur.execute(stmt_create)
# Connector/Python also allows ? as placeholders for MySQL Prepared
# statements.
prepstmt = "INSERT INTO names (name) VALUES (%s)"
# Preparing the statement is done only once. It can be done before
# without data, or later with data.
curprep.execute(prepstmt)
# Insert 3 records
names = ('Geert', 'Jan', 'Michel')
for name in names:
curprep.execute(prepstmt, (name,))
cnx.commit()
# We use a normal cursor issue a SELECT
output.append("Inserted data")
cur.execute("SELECT id, name FROM names")
for row in cur:
output.append("{0} | {1}".format(*row))
# Cleaning up, dropping the table again
cur.execute(stmt_drop)
cnx.close()
return output
if __name__ == '__main__':
config = {
'host': 'localhost',
'port': 3306,
'database': 'test',
'user': 'root',
'password': '',
'charset': 'utf8',
'use_unicode': True,
'get_warnings': True,
}
out = main(config)
print('\n'.join(out))

View File

@@ -0,0 +1,137 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
Example using MySQL Connector/Python showing:
* dropping and creating a table
* using warnings
* doing a transaction, rolling it back and committing one.
"""
import mysql.connector
def main(config):
output = []
db = mysql.connector.Connect(**config)
cursor = db.cursor()
# Drop table if exists, and create it new
stmt_drop = "DROP TABLE IF EXISTS names"
cursor.execute(stmt_drop)
stmt_create = """
CREATE TABLE names (
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(30) DEFAULT '' NOT NULL,
cnt TINYINT UNSIGNED DEFAULT 0,
PRIMARY KEY (id)
) ENGINE=InnoDB"""
cursor.execute(stmt_create)
warnings = cursor.fetchwarnings()
if warnings:
ids = [ i for l,i,m in warnings]
output.append("Oh oh.. we got warnings..")
if 1266 in ids:
output.append("""
Table was created as MYISAM, no transaction support.
Bailing out, no use to continue. Make sure InnoDB is available!
""")
db.close()
return
# Insert 3 records
output.append("Inserting data")
names = ( ('Geert',), ('Jan',), ('Michel',) )
stmt_insert = "INSERT INTO names (name) VALUES (%s)"
cursor.executemany(stmt_insert, names)
# Roll back!!!!
output.append("Rolling back transaction")
db.rollback()
# There should be no data!
stmt_select = "SELECT id, name FROM names ORDER BY id"
cursor.execute(stmt_select)
rows = None
try:
rows = cursor.fetchall()
except mysql.connector.InterfaceError as e:
raise
if rows == []:
output.append("No data, all is fine.")
else:
output.append("Something is wrong, we have data although we rolled back!")
output.append(rows)
cursor.close()
db.close()
return output
# Do the insert again.
cursor.executemany(stmt_insert, names)
# Data should be already there
cursor.execute(stmt_select)
output.append("Data before commit:")
for row in cursor.fetchall():
output.append("%d | %s" % (row[0], row[1]))
# Do a commit
db.commit()
cursor.execute(stmt_select)
output.append("Data after commit:")
for row in cursor.fetchall():
output.append("%d | %s" % (row[0], row[1]))
# Cleaning up, dropping the table again
cursor.execute(stmt_drop)
cursor.close()
db.close()
return output
if __name__ == '__main__':
config = {
'host': 'localhost',
'port': 3306,
'database': 'test',
'user': 'root',
'password': '',
'charset': 'utf8',
'use_unicode': True,
'get_warnings': True,
}
out = main(config)
print('\n'.join(out))

View File

@@ -0,0 +1,97 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
Example using MySQL Connector/Python showing:
* the usefulness of unicode, if it works correctly..
* dropping and creating a table
* inserting and selecting a row
"""
import mysql.connector
info = """
For this to work you need to make sure your terminal can output
unicode character correctly. Check if the encoding of your terminal
is set to UTF-8.
"""
def main(config):
output = []
db = mysql.connector.Connect(**config)
cursor = db.cursor()
# Show the unicode string we're going to use
unistr = u"\u00bfHabla espa\u00f1ol?"
output.append("Unicode string: %s" % unistr)
# Drop table if exists, and create it new
stmt_drop = "DROP TABLE IF EXISTS unicode"
cursor.execute(stmt_drop)
stmt_create = (
"CREATE TABLE unicode ("
" id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, "
" str VARCHAR(50) DEFAULT '' NOT NULL, "
" PRIMARY KEY (id)"
") CHARACTER SET 'utf8'"
)
cursor.execute(stmt_create)
# Insert a row
stmt_insert = "INSERT INTO unicode (str) VALUES (%s)"
cursor.execute(stmt_insert, (unistr,))
# Select it again and show it
stmt_select = "SELECT str FROM unicode WHERE id = %s"
cursor.execute(stmt_select, (1,))
row = cursor.fetchone()
output.append("Unicode string coming from db: " + row[0])
# Cleaning up, dropping the table again
cursor.execute(stmt_drop)
cursor.close()
db.close()
return output
if __name__ == '__main__':
config = {
'host': 'localhost',
'port': 3306,
'database': 'test',
'user': 'root',
'password': '',
'charset': 'utf8',
'use_unicode': True,
'get_warnings': True,
}
out = main(config)
print('\n'.join(out))

View File

@@ -0,0 +1,79 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import sys, os
import mysql.connector
"""
Example using MySQL Connector/Python showing:
* using warnings
"""
STMT = "SELECT 'abc'+1"
def main(config):
output = []
config['get_warnings'] = True
db = mysql.connector.Connect(**config)
cursor = db.cursor()
db.sql_mode = ''
output.append("Executing '%s'" % STMT)
cursor.execute(STMT)
cursor.fetchall()
warnings = cursor.fetchwarnings()
if warnings:
for w in warnings:
output.append("%d: %s" % (w[1],w[2]))
else:
output.append("We should have got warnings.")
raise Exception("Got no warnings")
cursor.close()
db.close()
return output
if __name__ == '__main__':
#
# Configure MySQL login and database to use in config.py
#
config = {
'host': 'localhost',
'port': 3306,
'database': 'test',
'user': 'root',
'password': '',
'charset': 'utf8',
'use_unicode': True,
'get_warnings': True,
}
out = main(config)
print('\n'.join(out))