翡翠谷 2019-12-22
pymysql安装及python数据库连接
pip install PyMSQL import pymysql db = pymysql.connect(‘数据库ip‘,‘用户‘,‘密码‘,‘数据库‘) #打开数据库连接 cursor.execute(‘select version()‘) #使用execute()方法执行sql语句 data = cursor.fetchone() #使用fetchone()方法获取单条数据 print(‘database version:%s‘%data) db.close #关闭数据库连接
创建表操作
import pymysql db = pymsql.connect(‘localhost‘,‘testuser‘,‘test123‘,‘testdb‘) #打开数据库连接 cursor = db.cursor() #使用cursor()方法创建一个游标对象 cursor cursor.execute(‘drop table if exists employee‘) #使用execute()方法执行sql,如果表存在则删除 sql = ‘‘‘create table employee(first_name char(20) not null,last_name char(20),age int,sex char(1),income float)‘‘‘ cursor.execute(sql) db.close() #关闭数据库连接
操作数据
#插入操作
import pymysql
db = pymysql.connect(‘localhost‘,‘testuser‘,‘test123‘,‘testdb‘) #打开数据库连接
cursor = db.cursor() #使用cursor()方法获取操作游标
sql1 = ‘‘‘insert into employee(first_name,last_name,age,sex,income) values(‘mac‘,‘mohan‘,20,‘m‘,2000)‘‘‘#sql插入语句
try:
    cursor.execute(sql) #执行sql语句
    db.commit() #提交到数据库执行
except:
    db.rollback() #如果发生错误则回滚
#查询操作
sql2 = ‘select * from employee where incom >%s‘%(1000)
try:
    cursor.execute(sql) #执行sql语句
    results = cursor.fetchall() #获取所有记录列表
    for now in results:
        fname = row[0]
        lname = row[1]
        age = row[2]
        sex = row[3]
        income = row[4]
        print(‘fname = %s,lname = %s,age = %s,incom = %s‘)%(fname,lname,age,sex,income)
except:
    print(‘Error:unable to fetch data‘)
db.close() #关闭数据库
#更新操作
sql3 = (‘update employee set age = age+1 where sex = %s‘)%(‘M‘)
try:
    cursor.execute(sql)
    db.commit() #提交到数据库执行
except:
    db,rollback()
db.close()
#删除操作
sql4 = ‘delete from employee where age>%s‘%20
try:
    cursor.execute(sql)
    db.commit
except:
    db.rollback()
db.close数据库备份
#单库备份 mysqldump -uroot -p123 db1 > db1.sql #mysqldump -h 服务器 -u用户名 -p密码 数据库名 > 备份文件.sql mysqldump -uroot -p123 db1 table1 table2 > db1-table1-table2.sql #多库备份 mysqldump -uroot -p123 --databases db1 db2 mysql db3 > db1_db2_mysql_db3.sql #备份所有库 mysqldump -uroot -p123 --all-databases > all.sql