python + MySql 基本操作

python + mysql数据库的链接

1、安装mysql

pip install PySQLdb

2、连接数据库

# -*- coding: UTF-8 -*-

import MySQLdb

# 打开数据库连接
db = MySQLdb.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='gz_information', charset='utf8')

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# 使用execute方法执行SQL语句
cursor.execute("SELECT * FROM user")
data = cursor.fetchall()
# # 使用 fetchone() 方法获取一条数据
# data = cursor.fetchone()

print data

# 关闭数据库连接
db.close()

3、插入数据

insert = "insert into user(username, password) values('aaaa','aaaa')"
print insert
cursor.execute(insert)
db.commit()  #将插入的数据提交至数据库执行

4、删除数据

de = "delete from user where username = 'aaaa'"
print de
cursor.execute(de)
db.commit()

5、更新数据

update = "update user set password='123123' where username = '1'"
print update
cursor.execute(update)
db.commit()

猜你喜欢

转载自www.cnblogs.com/juan-F/p/10310445.html