pip install --upgrade pip
pip install PyMySQL
sudo service mysql start
mysql -uroot -p
create database mydb;
use mydb;
create table employee(first_name varchar(20),last_name varchar(20),age int,income float);
import pymysql
db = pymysql.connect(“localhost”,“root”,“strongs”,“testdb” )
cursor = db.cursor()
cursor.execute(“select version()”)
data = cursor.fetchone()
print ("Database version : %s " % data)
db.close()
7.import pymysql
db = pymysql.connect(“localhost”,“root”,“strongs”,“testdb” )
cursor = db.cursor()
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:
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()
import pymysql
db = pymysql.connect(“localhost”,“root”,“strongs”,“testdb” )
cursor = db.cursor()
sql = “update employee set age = age + 1 where sex = ‘%c’” % (‘M’)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
print(‘update success!’)
import pymysql
db = pymysql.connect(“localhost”,“root”,“strongs”,“testdb” )
cursor = db.cursor()
sql = “delete from employee where age > ‘%d’” % (20)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
print(‘delete success!’)