MySQL Connector/Python for Python 3.3_MySQL
import mysql.connector
import sys, os
user = 'root'
pwd = '123456'
host = 'local.dba.tt'
db = 'test'
data_file = 'mysql-test.dat'
create_table_sql = "CREATE TABLE IF NOT EXISTS mytable ( /
id int(10) AUTO_INCREMENT PRIMARY KEY, /
name varchar(20), age int(4) ) /
CHARACTER SET utf8"
insert_sql = "INSERT INTO mytable(name, age) VALUES ('Jay', 22 ), ('杰', 26)"
select_sql = "SELECT id, name, age FROM mytable"
cnx = mysql.connector.connect(user=user, password=pwd, host=host, database=db)
cursor = cnx.cursor()
try:
cursor.execute(create_table_sql)
except mysql.connector.Error as err:
print("create table 'mytable' failed.")
print("Error: {}".format(err.msg))
sys.exit()
try:
cursor.execute(insert_sql)
except mysql.connector.Error as err:
print("insert table 'mytable' failed.")
print("Error: {}".format(err.msg))
sys.exit()
if os.path.exists(data_file):
myfile = open(data_file)
lines = myfile.readlines()
myfile.close()
for line in lines:
myset = line.split()
sql = "INSERT INTO mytable (name, age) VALUES ('{}', {})".format(myset[0], myset[1])
try:
cursor.execute(sql)
except mysql.connector.Error as err:
print("insert table 'mytable' from file 'mysql-test.dat' -- failed.")
print("Error: {}".format(err.msg))
sys.exit()
try:
cursor.execute(select_sql)
for (id, name, age) in cursor:
print("ID:{} Name:{} Age:{}".format(id, name, age))
except mysql.connector.Error as err:
print("query table 'mytable' failed.")
print("Error: {}".format(err.msg))
sys.exit()
cnx.commit()
cursor.close()
cnx.close()
推荐阅读
-
用Python的Flask框架结合MySQL写一个内存监控程序
-
python使用MySQLdb访问mysql数据库的方法
-
Python连接mysql数据库及python使用mysqldb连接数据库教程
-
Python中MySQLdb和torndb模块对MySQL的断连问题处理
-
Windows7下Python3.4使用MySQL数据库
-
python安装mysql-python简明笔记(ubuntu环境)
-
python连接mysql调用存储过程示例
-
python连接mysql并提交mysql事务示例
-
python基于mysql实现的简单队列以及跨进程锁实例详解
-
用python简单实现mysql数据同步到ElasticSearch的教程