python 操作数据库,, pymysql安
python 操作数据库,, pymysql安
pymysql安装及python数据库连接
pip install PyMSQLimport pymysqldb = pymysql.connect(‘数据库ip‘,‘用户‘,‘密码‘,‘数据库‘) #打开数据库连接cursor.execute(‘select version()‘) #使用execute()方法执行sql语句data = cursor.fetchone() #使用fetchone()方法获取单条数据print(‘database version:%s‘%data)db.close #关闭数据库连接
创建表操作
import pymysqldb = pymsql.connect(‘localhost‘,‘testuser‘,‘test123‘,‘testdb‘) #打开数据库连接cursor = db.cursor() #使用cursor()方法创建一个游标对象 cursorcursor.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 pymysqldb = 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‘%20try: cursor.execute(sql) db.commitexcept: db.rollback()db.close
数据库备份
#单库备份mysqldump -uroot -p123 db1 > db1.sql #mysqldump -h 服务器 -u用户名 -p密码 数据库名 > 备份文件.sqlmysqldump -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
python 操作数据库
评论关闭