前言:python如果想要连接到MySQL要安装上相关的驱动才下;好在驱动程序在mysql的官网可以下载的到。
以下是我自己保存的一个conetos7版本
http://yunpan.cn/cLACS7VurfaE4 访问密码 2e26
例子:
#!/usr/bin/python
#!coding:utf-8 import mysql.connector
from mysql.connector import errorcode def create_db(host='127.0.0.1',port=3306,user='admin',password='',database='studio'):
config={
'host':host,
'port':port,
'user':user,
'password':password,
'database':database
}
try:
conn=mysql.connector.connect(**config)
except mysql.connector.Error,err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print 'ACCESS_DENIED_ERROR something is worng your name or password'
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print 'database is not exists'
else:
print err
else:
print 'linked to database...'
cursor=conn.cursor()
create_db='create database if not exists tempdb character set utf8;'
cursor.execute(create_db)
print 'database been created ...'
conn.close() if __name__=="__main__":
create_db()