在python中使用mysql数据库
先用pip安装一下mysql
pip install pymysql
使用的时候,import python
import pymysql
###python连接数据库操作
# 打开数据库连接
def connectdb():
print('连接到mysql服务器...')
db = pymysql.connect("localhost","你的mysql用户名","你的mysql密码","数据库" )
return db
#插入数据
def insert(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句,我的数据库是post
sql="INSERT INTO post\
value('1','A','it')"
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
#删除数据
def delete(db):
cursor = db.cursor()
sql="delete from post where uid='3'"
try:
cursor.execute(sql)
db.commit()
except:
print('did not delete it !')
db.rollback()
#更新数据
def updatedb(db):
cursor=db.cursor()
sql="update post set uname='update' where uid='4'"
try:
cursor.execute(sql)
db.commit()
except:
print('did not updatedb!')
db.rollback()
def query(db):
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
sql = "SELECT * FROM post "\
try:
# 执行SQL语句
cursor.execute(sql)
db.commit()
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
uid = row[0]
uname = row[1]
content = row[2]
# 打印结果
print ("uid=%d,uname=%s,content=%s" % \
(uid, uname, content))
except:
print ("Error: unable to fetch data")
#关闭连接
def closedb(db):
db.close()
def main():
db = connectdb()
insert(db)
delete(db)
updatedb(db)
query(db)
closedb(db)
if __name__=='__main__':
main()
我的数据库是post 字段名是uid uname content,先自行设置下。
学习的时候记得别直接复制代码。比如,需要有数据才可以删除........学习必须思考啊~
以上就是python的使用。是不是很简单。
还不是mysql的那种使用方法:增删改更新。然后对数据的连接,事务的提交,事务的回滚以及对事务提交,最后还有关闭。
SQL语言的操作,还是要看手册:
http://www.w3school.com.cn/sql/index.asp
版权声明:本文为博主原创文章,未经博主允许不得转载。https://mp.csdn.net/postedit/81175765