Python-MySql

连接数据库

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

上一篇:常见数据库会话查询脚本


下一篇:DB性能瓶颈分析思路