您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

python怎么连接mysql

2024/2/24 10:41:38发布11次查看
python怎么连接mysql?下面给大家具体介绍mysqldb的使用方法:
(1) 什么是mysqldb?
mysqldb是用于python连接mysql数据库的接口,它实现了python数据库api规范 v2.0,基于mysql c api 上建立的。
(2) 源码安装 mysqldb: https://pypi.python.org/pypi/mysql-python
$ tar zxvf mysql-python-*.tar.gz$ cd mysql-python-*$ python setup.py build$ python setup.py install
相关推荐:《python视频教程》
(3) mysqldb 的使用:
#!/usr/bin/env python# coding=utf-8import mysqldbdef connectdb(): print('连接到mysql服务器...') # 打开数据库连接 # 用户名:hp, 密码:hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库testdb, 并在testdb数据库中创建好表student db = mysqldb.connect("localhost","hp","hp12345.","testdb") print('连接上了!') return dbdef createtable(db): # 使用cursor()方法获取操作游标 cursor = db.cursor() # 如果存在表sutdent先删除 cursor.execute("drop table if exists student") sql = """create table student ( id char(10) not null, name char(8), grade int )""" # 创建sutdent表 cursor.execute(sql)def insertdb(db): # 使用cursor()方法获取操作游标 cursor = db.cursor() # sql 插入语句 sql = """insert into student values ('001', 'czq', 70), ('002', 'lhq', 80), ('003', 'mq', 90), ('004', 'wh', 80), ('005', 'hp', 70), ('006', 'yf', 66), ('007', 'test', 100)""" #sql = "insert into student(id, name, grade) \ # values ('%s', '%s', '%d')" % \ # ('001', 'hp', 60) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: # rollback in case there is any error print '插入数据失败!' db.rollback()def querydb(db): # 使用cursor()方法获取操作游标 cursor = db.cursor() # sql 查询语句 #sql = "select * from student \ # where grade > '%d'" % (80) sql = "select * from student" try: # 执行sql语句 cursor.execute(sql) # 获取所有记录列表 results = cursor.fetchall() for row in results: id = row[0] name = row[1] grade = row[2] # 打印结果 print "id: %s, name: %s, grade: %d" % \ (id, name, grade) except: print "error: unable to fecth data"def deletedb(db): # 使用cursor()方法获取操作游标 cursor = db.cursor() # sql 删除语句 sql = "delete from student where grade = '%d'" % (100) try: # 执行sql语句 cursor.execute(sql) # 提交修改 db.commit() except: print '删除数据失败!' # 发生错误时回滚 db.rollback()def updatedb(db): # 使用cursor()方法获取操作游标 cursor = db.cursor() # sql 更新语句 sql = "update student set grade = grade + 3 where id = '%s'" % ('003') try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: print '更新数据失败!' # 发生错误时回滚 db.rollback()def closedb(db): db.close()def main(): db = connectdb() # 连接mysql数据库 createtable(db) # 创建表 insertdb(db) # 插入数据 print '\n插入数据后:' querydb(db) deletedb(db) # 删除数据 print '\n删除数据后:' querydb(db) updatedb(db) # 更新数据 print '\n更新数据后:' querydb(db) closedb(db) # 关闭数据库if __name__ == '__main__': main()
以上就是python怎么连接mysql的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product