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()

猜你喜欢

转载自www.cnblogs.com/huaerye/p/13209662.html