読者です 読者をやめる 読者になる 読者になる

MySQL Connector/Python Examples

python 2.7.3
MySQL Connector/Python 1.0.9

MySQL :: MySQL 5.5 Reference Manual :: 22.6.4 Connector/Python Coding Examples
基本はここみれば、わかるけどurl先のexample通りにやったら err.errmsg はないって言われた

import mysql.connector

# table sql
tables ={}
tables["test_table"] = (
	"create table test_table ("
	"	id int not null auto_increment,"
	"	champion_name char(255) not null,"
	"	number int not null,"
	"	primary key(id)"
	")"
)

cnx = mysql.connector.connect(user="crawler",password="pass1234",host="localhost",database="test_crawler")
cursor = cnx.cursor()

# create table
for name, ddl in tables.iteritems():
	try:
		print("Creating table {}:".format(name))
		cursor.execute(ddl)
	except mysql.connector.Error as err:
		if err.errno == mysql.connector.errorcode.ER_TABLE_EXISTS_ERROR:
			print("already exists.")
		else:
			print(err)
	else:
		print("OK")
		
# insert
# insert template
add_test_table = (
	"insert into test_table "
	"(champion_name, number) "
	"values (%(champion_name)s, %(number)s)"
)
data_test_table = {
	"champion_name":"xerath",
	"number":20
}
cursor.execute(add_test_table, data_test_table)

cnx.commit()

# select
query = ("select champion_name, number from test_table")
cursor.execute(query)
for (champion_name, number) in cursor:
	print champion_name, number

cursor.close()
cnx.close()