• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
花儿爷
博客园    首页    新随笔    联系   管理     
python_连接mysql

使用cursor对象的execute()方法具体执行数据库的操作;

对于插入、更新、删除等操作,需要使用db.commit()来提交到数据库执行,对于查询、创建数据库和数据表的操作不需要此语句。

import pymysql

db = pymysql.connect(host = 'localhost',port = 3306,user = 'root',passwd = 'root',db = 'test1',charset = 'utf8')

cursor = db.cursor()   #使用cursor方法创建一个游标

#使用execute()方法来实现对数据库的基本操作。
# cursor.execute("select version()")
# data = cursor.fetchone()
# print("数据库的版本号为:%s" % data)

#创建数据库
# cursor.execute("drop database if exists test1")   #如果数据库已经存在,那么删除后重新创建
# sql = "create database test1"
# cursor.execute(sql)


#创建数据库表
# cursor.execute("drop table if exists employee")
# sql = """
# CREATE TABLE EMPLOYEE (
# FIRST_NAME CHAR(20) NOT NULL,
# LAST_NAME CHAR(20),
# AGE INT,
# SEX CHAR(1),
# INCOME FLOAT )
# """
# cursor.execute(sql)

#查询数据表数据
# sql = "select * from employee"
# cursor.execute(sql)
# data = cursor.fetchone()      #查询一条数据
# data = cursor.fetchall()      #查询所有数据
# print(data)

#指定条件查询数据表数据

# sql = " select * from employee where income > '%d' " % (1000)
#
# cursor.execute(sql)
#
# data = cursor.fetchone()
#
# print(data)

#插入数据
# sql = "insert into employee values ('bb','bb',20,'W',5000)"
# cursor.execute(sql)
# db.commit()

#更新数据库

# sql = " update employee set age = age+1 where sex = '%c' " % ('W')
#
# cursor.execute(sql)
#
# db.commit()

#删除数据
#
# sql = " delete from employee where age > '%d' " % (30)
#
# cursor.execute(sql)
#
# db.commit()
db.close()

 

posted on 2020-06-29 18:40  flowerszhao  阅读(147)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3