python利用PyMySQL操作

1.首先要安装pycharm。升级pip和安装PyMySQL 打开命令行

pip install --upgrade pip
pip install PyMySQL

2.开启mysql服务

sudo service mysql start

3.开启mysql

mysql -uroot -p

4.创建数据库mydb并使用

create database mydb;
use mydb;

5.创建employee表

create table employee(first_name varchar(20),last_name varchar(20),age int,income float);

6.接下来要在pycharm利用PyMySQL

import pymysql

打开数据库连接

db = pymysql.connect(“localhost”,“root”,“strongs”,“testdb” )

使用 cursor() 方法创建一个游标对象 cursor

cursor = db.cursor()

使用 execute() 方法执行 SQL 查询

cursor.execute(“select version()”)

使用 fetchone() 方法获取单条数据.

data = cursor.fetchone()

print ("Database version : %s " % data)

关闭数据库连接

db.close()
7.import pymysql

打开数据库连接

db = pymysql.connect(“localhost”,“root”,“strongs”,“testdb” )

使用 cursor() 方法创建一个游标对象 cursor

cursor = db.cursor()

使用 execute() 方法执行 SQL,如果表存在则删除

cursor.execute(“drop table if exists employee”)

使用预处理语句创建表

sql = “”“create table employee(
first_name varchar(20) not null,
last_name varchar(20),
age int,
sex char(5),
income float )”""
print(‘create success!’)
cursor.execute(sql)

关闭数据库连接

db.close()

8.查询
Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。

fetchone():该方法获取下一个查询结果集。结果集是一个对象
fetchall():接收全部的返回结果行。
rowcount:这是一个只读属性,并返回执行execute()方法后影响的行数。

import pymysql
db = pymysql.connect(“localhost”,“root”,“strongs”,“testdb” )
cursor = db.cursor()
sql = “select * from employee \
where age > ‘%d’” % (18)
try:

执行SQL语句

cursor.execute(sql)

获取所有记录列表

results = cursor.fetchall()
for row in results:
first_name = row[0]
last_name = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 打印结果
print (“fname=%s,lname=%s,age=%d,sex=%s,income=%d” % \
(first_name, last_name, age, sex, income ))
except:
print (“Error: unable to fetch data”)
db.close()

9.更新数据

import pymysql
db = pymysql.connect(“localhost”,“root”,“strongs”,“testdb” )
cursor = db.cursor()
sql = “update employee set age = age + 1 where sex = ‘%c’” % (‘M’)
try:

执行SQL语句

cursor.execute(sql)

提交到数据库执行

db.commit()
except:

发生错误时回滚

db.rollback()
db.close()
print(‘update success!’)

10删除数据

import pymysql
db = pymysql.connect(“localhost”,“root”,“strongs”,“testdb” )
cursor = db.cursor()
sql = “delete from employee where age > ‘%d’” % (20)
try:

执行SQL语句

cursor.execute(sql)

提交修改

db.commit()
except:

发生错误时回滚

db.rollback()
db.close()
print(‘delete success!’)

你可能感兴趣的:(pymysql)