python对数据库的操作

python对数据库的操作

一. 安装数据库API接口

pip install PyMySQL

二. 对数据库进行查询的操作

import pymysql  #导入数据库接口库
db = pymysql.Connect(
    host = 'locaihost',
    user = 'root',
    passwd = '123456',
    db = 'company',
    port = 3306,
    charset = 'utf8'
)    #连接数据库(host:主机,user:用户,passwd:密码,db:数据库名字,port:端口号,)
cursor = db.cursor() # 获取游标
sql = ''' slect * from tb_dept ''' # 查询语句
cursor.execute(sql)   #执行查询语句
data = cursor.fetchall() # 返回结果(元组)
for i in data:
    print(i)
db.close()

三. 对数据库进行插入数据操作

import pymysql  #导入数据库接口库
db = pymysql.Connect(
    host = 'locaihost',
    user = 'root',
    passwd = '123456',
    db = 'company',
    port = 3306,
    charset = 'utf8'
)    #连接数据库(host:主机,user:用户,passwd:密码,db:数据库名字,port:端口号,)
cursor = db.cursor() # 获取游标
try:
    sql = ''' inset into grage values(8,'数学','高级班','2018-4-5') '''
    cursor.execte(sql)
    db.commit()
except:
     db.rollback()
data = cursor.fetchall()
db.close()

四.对数据库进行删除操作

import pymysql  #导入数据库接口库
db = pymysql.Connect(
    host = 'locaihost',
    user = 'root',
    passwd = '123456',
    db = 'company',
    port = 3306,
    charset = 'utf8'
)    #连接数据库(host:主机,user:用户,passwd:密码,db:数据库名字,port:端口号,)
cursor = db.cursor() # 获取游标
try:
    sql = ''' delete from tb_dept where deptno = 10 '''
    cursor.excute(sql)
    db.commit
except:
    db.rollback()
db.close()

你可能感兴趣的:(python)