首页 > 数据库技术 > 详细

Python-MySql

时间:2021-04-03 12:59:12      阅读:25      评论:0      收藏:0      [点我收藏+]

连接数据库

import pymysql
db = pymysql.connect("localhost","username","password","db_name",charset="utf-8")
#获取游标
cursor = db.cursor()
#数据库操作语句.......
db.close()

建表

sql = """
create table employee(
first_name char(20) NOT NULL,
last_name char(20) NOT NULL,
age int,
sex char(1),
income float)
"""
cursor.execute(sql)

sql = """
insert into
employee(first_name,last_name,age,sex,income)
values(‘hug‘,‘boy‘,20,‘M‘,2001)
"""
try:
    cursor.execute(sql)
    db.commit()
except:
      #发生错误回滚
      db.rollback()

sql = """
delete from employee where age > %s" % (20)
try:
    cursor.execute(sql)
    db.commit()
except:
      db.rollback()

sql = "updata employee set age = age + 2 where sex = ‘%c‘ " % (‘M‘)
try:
    cursor.execute(sql)
    db.commit()
except:
      db.rollback()

sql = """
select * from employee where income > %s" %(1000)
"""

try:
    cursor.execute(sql)
    #获取所有记录
    results = cursor.fetchall()
    for row in results:
       fname = row[0]
       lname = row[1]
       age = row[2]
       sex = row[3]
       income = row[4]
       print("fname=%s,lname=%s,age=%s,sex=%s,income=%s" %            (fname,lname,age,sex,income))
except:
      print("Error: unable to feth data")

Python-MySql

原文:https://www.cnblogs.com/hugboy/p/python_mysql.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!