Python DB-API
python标准数据库接口是python DB-API,为开发人员提供了数据库应用编程接口。
利用python来对MySQL数据库进行操作。
安装mySQLdb:
在cmd中pip install mysqlclient
在pycharm中import MySQLdb可以成功导入说明安装成功。
数据库操作
连接数据库:
import MySQLdb
#打开数据库连接
db=MySQLdb.connect(host=””,user=””,password=””,port=,db=””,charset=’utf8’)
#使用cursor()方法来获取操作游标
cursor=db.cursor()
#使用execute方法执行SQL语句
cursor.execute(“SELECT * FROM 表名”)
#使用fetchone()方法获取一条数据
data=cursor.fetchone()
data2=cursor.fetchall()#获取所有数据
data3=cursor.fetchmany(X)#获取X条数据
#关闭数据库连接
cursor.close()
db.close()
创建表:
import MySQLdb
db=MySQLdb.connect(host=””,user=””,password=””,port=,db=””,charset=’utf8’)
#使用cursor()方法来获取操作游标
cursor=db.cursor()
sql=”CREATE TABLE 表名 (‘id’ int(10) DEFAULT NULL,’name’ varchar(25) DEFAULT NULL,’age’ int(100) DEFAULT NULL,PRIMARY KEY(‘id’))”
cursor.execute(sql)
cursor.close()
conn.commit()#提交到数据库
conn.close()
插入数据:
import MySQLdb
db=MySQLdb.connect(host=””,user=””,password=””,port=,db=””,charset=’utf8’)
#使用cursor()方法来获取操作游标
cursor=db.cursor()
insert=cursor.execeute(“insert into 表名 values(1,’tom’,18)”)
cursor.close()
conn.commit()#提交到数据库
conn.close()
查询数据:
cursor对象提供了3种提取数据的方法:fetchone、fetchall、fetchmany。
cursor.Fetchone():获取游标所在处的一行数据。返回元组,没有返回None。
cursor.fetchmany(size):接受size行返回结果行。
cursor.fetchall():接收全部的返回结果行。
更新数据:
import MySQLdb
db=MySQLdb.connect(host=””,user=””,password=””,port=,db=””,charset=’utf8’)
#使用cursor()方法来获取操作游标
cursor=db.cursor()
update=cursor.execute(“update 表名 set age=100 where name=’tom’”)
cursor.close()
conn.commit()#提交到数据库
conn.close()
删除数据:
import MySQLdb
db=MySQLdb.connect(host=””,user=””,password=””,port=,db=””,charset=’utf8’)
#使用cursor()方法来获取操作游标
cursor=db.cursor()
cursor.execute(“delete from 表名 where 条件”)
cursor.close()
conn.commit()#提交到数据库
conn.close()