使用python去操作数据库(比命令行操作数据库简单)
python 安装第三方库:
python2: pip install pymysql
import MySQLdb
DATABASE = {
'host': '12.0.0.1', #
'database': 'examination' , #如果为远程数据库,此处为远程服务器的ip地址
'user': 'root',
'password': '123456'
'charset': 'utf8mb4'
}
# db = MySQLdb.connect(host= 'localhost', user= 'root' , password='123456',database='examination' )
# 等价于
db = MySQLdb.connect( 'localhost', 'root' , '123456', 'examination' )
# 等价于
db = MySQLdb.connect(**DATABASE)
# python3: pip install mysqlclient
游标
cursor = db.cursor()
查询
sql ="select * from class"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(row)
(1, '?????')#由于未指定编码格式 解决方式:DATABASE 中加入: 'charset': 'utf8mb4'
(1, '高一一班')