概述
Python操作mysql数据库
import pymysql
def createUserTable():
conn = pymysql.connect('localhost', user="root", passwd="123456", db="test_zheng")
cursor = conn.cursor()
cursor.execute('drop table if exists user')
sql = """ CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"""
cursor.execute(sql)
cursor.close() # 先关闭游标
conn.close() # 再关闭数据库连接
print('创建数据表成功')
def insertUser():
conn = pymysql.connect('localhost',user = "root",passwd = "123456",db = "test_zheng")
cursor = conn.cursor()
insert = cursor.execute("INSERT into user (`name` ,age) VALUES ('tom',18);")
cursor.close()
conn.commit()
conn.close()
print('添加语句受影响的行数:', insert)
def insertUser2():
conn = pymysql.connect('localhost',user = "root",passwd = "123456",db = "test_zheng")
cursor = conn.cursor()
sql = "INSERT into user (`name` ,age) VALUES (%s,%s)"
insert = cursor.execute(sql,("Jeff.zheng",18))
cursor.close()
conn.commit()
conn.close()
print('添加语句受影响的行数:', insert)
def updateUser():
conn = pymysql.connect('localhost',user = "root",passwd = "123456",db = "test_zheng")
cursor = conn.cursor()
sql = "UPDATE `user` set age =21 where name='Jeff.zheng'"
insert = cursor.execute(sql)
cursor.close()
conn.commit()
conn.close()
print('添加语句受影响的行数:', insert)
def selectUser():
conn = pymysql.connect('localhost',user = "root",passwd = "123456",db = "test_zheng")
cursor = conn.cursor()
sql = "select * from user"
result = cursor.execute(sql)
while 1 :
res=cursor.fetchone()
if res is None:
break
else:
print(res)
cursor.close()
conn.commit()
conn.close()
print('添加语句受影响的行数:',result)
if __name__ == '__main__':
# createUserTable()
selectUser()
不行的话就是pip install pymysql
下载一下依赖
最后
以上就是笨笨飞鸟为你收集整理的Python操作mysql数据库的全部内容,希望文章能够帮你解决Python操作mysql数据库所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复