您的位置:首页 > 编程语言 > Python开发

python 连接数据库练习

2017-10-18 16:13 435 查看
#!/usr/bin/python
# -*- coding:utf-8 -*-
import logging
logging.basicConfig(level=logging.INFO)
import mysql.connector
import json
def selectmysql():
try:
conn = mysql.connector.connect(host='ip',port=端口号,user='test',passwd='test123456',db='test', use_unicode=True)
cursor = conn.cursor()
data = []
for index in range(1,100):
# 插入一行记录,注意MySQL的占位符是%s:
cursor.execute('select id from user where id = "%s" '% index )
# 查询单数据时用

id = cursor.fetchone()

# id = cursor.fetchall() 查询多数据时使用

#去除为空的数据

if id != None:
data.append(wmid)

print data #打印的数据结果为数组
print json.dumps(data) #转换为json格式

except mysql.connector.Error as e:
print ('Error : {}'.format(e))
finally:
conn.commit()
cursor.close
conn.close
print 'Connect test closed in finally'

'''

'cursor.execute('insert into test (id, name) values (%s, %s)', ['1', 'Michael'])
cursor.rowcount

# 提交事务:
conn.commit()
cursor.close()

'''
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: