python版本 2.7.1,python 连接mysql需要安装MYSQLdb模块
安装方法一种是cmd pip命令安装
pip install MySQLdb
一种是网上下载python MYSQLdb模块包 放到python 安装目录下的lib文件夹
安装成功后在cmd命令
python #进入python 交互模式 import MySQLdb #没有报错说明安装成功
#python 连接mysql并且导入数据表users代码
#coding:utf-8
import MySQLdb try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='你的密码',db='local_db',port=3306,charset='utf8')
with conn:
cursor=conn.cursor()
sql='''
SELECT username,CONCAT(RIGHT(address,1),"测试",LEFT(address,1)) AS address,
CASE WHEN telephone IS NOT NULL THEN CONCAT(LEFT(telephone,3),58568, RIGHT(telephone,2)) ELSE NULL END AS telephone
FROM a001_resterant
WHERE username IN (SELECT username FROM test_a03order GROUP BY username)
'''
count=cursor.execute(sql)
conn.commit()
data=cursor.fetchall()
for i in data:
print i[0],i[1],i[2]
cursor.execute("INSERT INTO users (username,address,telephone) values(%s,%s,%s)",(i[0],i[1],i[2]))
conn.commit()
print "输入了"+str(count)+"条数据"
except MySQLdb.Error:
print "连接失败!"