# -*- coding: UTF-8 -*-
import MySQLdb
# 数据库参数
user = 'root'
pwd = '******'
host = 'localhost'
db = 'pythonTest'
# # 创建数据库
# createDB="create database pythonTest"
#
# try:
# connect = MySQLdb.connect(host=host, user=user, passwd=pwd)
# cursor = connect.cursor()
# cursor.execute(createDB)
# except Exception as e:
# print e
#
# 连接已存在的数据库
try:
connect = MySQLdb.connect(host=host,user=user,passwd=pwd,db=db)
cursor = connect.cursor()
except Exception as e:
print e
# # 删除数据库
# deleteDB="drop database pythonTest1"
#
# try:
# connect = MySQLdb.connect(host=host, user=user, passwd=pwd)
# cursor = connect.cursor()
# print "数据库连接成功"
# except Exception as e:
# print e
#
#
# try:
# cursor.execute(deleteDB)
# except Exception as e:
# print e
#判断表是否存在
def existTable(cursor,name):
selectTab = 'select * from %s' % (name)
try:
cursor.execute(selectTab)
rows= cursor.fetchall()
return True
except Exception as e:
return False
# 创建表
exist = existTable(cursor,'user')
if exist == False:
createTab = "create table user1 if NOT EXISTS (id int NOT NULL ,name VARCHAR(45) NOT NULL ,PRIMARY KEY(id))"
try:
cursor.execute(createTab)
except Exception as e:
print e
# # 删除表
# dropTab = 'drop table user1'
#
# try:
# cursor.execute(dropTab)
# except Exception as e:
# print e
#
# 插入数据
if exist:
# # 单条插入
# insertTab = 'insert into user(id,name ) values(0, "name1") '
#
# try:
# cursor.execute(insertTab)
# connect.commit()
# except Exception as e:
# print e
# 多条插入
i = 1
insertTab = list()
insertTab = "insert into user(id,name ) values(%s,%s) "
insertArr = []
while i < 10:
insertArr.append((i, 'lv%s' % i))
i += 1
try:
print cursor.executemany(insertTab, insertArr)
connect.commit()
except (ZeroDivisionError, Exception) as e:
connect.rollback()
print e
# 查询数据
selectTab='select * from user'
try:
cursor.execute(selectTab)
# data = cursor.fetchone()
results = cursor.fetchall()
except Exception as e:
print e
for user in results:
print "id=%d name=%s" % (user[0],user[1])
# 删除数据
deleteTab = 'delete from user where id<11'
try:
cursor.execute(deleteTab)
connect.commit()
except Exception as e:
print e
# 关闭数据库连接
connect.close()
Python学习记录 - MySQL数据库
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 各位志同道合的同仁可以点击上方关注↑↑↑↑↑↑ 本教程致力于程序员快速掌握Python语言编程。 本文章内容是基于...
- 1.构造一个邮件对象就是一个Message对象 MIME - Multipurpose Internet Mail...
- 作者:姜健 链接:https://www.zhihu.com/question/34840297/answer/6...