Python操作数据库

时间:2022-09-12 15:42:10

 本文以mysql/mariadb为例

首先安装Python对mysql数据库的接口模块MySQLdb

pip install python-MySQL

1、插入数据:

import MySQLdb

conn
= MySQLdb.connect(
host
='localhost',
port
= 3306,
user
='root',
passwd
='密码',
db
='jwc2',
charset
='utf8'
)
cur
= conn.cursor()
sql
= "insert into cjcx_sc values(%s,%s,%s,%s)"
SC
= (id,Sno,Cname,Grade)
cur.execute(sql,SC)

conn.commit()
cur.close()
conn.close()

删除表中的一个字段:alter table 表名 drop column 字段名。。。。

2、查询数据:

#encoding=utf-8
import MySQLdb
import sys
reload(sys)
sys.setdefaultencoding(
'utf8')
conn
= MySQLdb.connect(
host
='localhost',
port
= 3306,
user
='root',
passwd
='211599100yxz',
db
='jwc2',
charset
='utf8'
)
cur
= conn.cursor()
try:
cur.execute(
"select Credit from cjcx_course")
Cname
= cur.fetchall()
for cname in Cname:
print cname[0]
conn.commit()
except Exception,ex:
print ex
finally:
cur.close()
conn.close()