首页 / PYTHON / 使用Python连接MySQL
使用Python连接MySQL
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用Python连接MySQL,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4067字,纯文字阅读大概需要6分钟。
内容图文
原文链接:https://blog.csdn.net/qq_41475058/article/details/907440531、连接数据库
import pymysql
#指定数据库地址、用户、密码、端口,使用connect()方法声明一个Mysql连接对象db
db = pymysql.connect(host='localhost',user='root', password='123456', port=3306)
#调用cursor()方法获得Mysql的操作游标,利用游标来执行SQL语句。
cursor = db.cursor()
#直接用execute()方法执行,第一句用于获得Mysql版本,然后调用fetchone()方法获得第一条数据。
cursor.execute('SELECT VERSION()')
data = cursor.fetchone()
print('Database version:', data)
##创建名称为spiders的数据库
cursor.execute("CREATE DATABASE spiders DEFAULT CHARACTER SET utf8")
db.close()
2、创建表
import pymysql
db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
cursor = db.cursor()
#创建一个名为students的数据表
sql = 'CREATE TABLE IF NOT EXISTS students (id VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, age INT NOT NULL, PRIMARY KEY (id))'
cursor.execute(sql)
db.close()
3、插入数据
import pymysql
#定义数据
id = '20120001'
user = 'Bob'
age = 20
#连接数据库
db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
cursor = db.cursor()
#使用格式化符%s来插入数据
sql = 'INSERT INTO students(id, name, age) values(%s, %s, %s)'
try:
cursor.execute(sql, (id, user, age))
db.commit()
except:
db.rollback()
db.close()
4、插入数据(字典)
import pymysql
#构造字典
data = {
'id': '20120001',
'name': 'Bob',
'age': 20
}
table = 'students'
#keys的结果是 id,name,age
keys = ', '.join(data.keys())
#values的结果是 %s, %s, %s
values = ', '.join(['%s'] * len(data))
#使用format()方法将表名、字段名和占位符构造出来。
#最终的SQL语句就被动态构造成 INSERT INTO students (id,name,age) VALUES (%s, %s, %s)
sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table, keys=keys, values=values)
db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
cursor = db.cursor()
try:
if cursor.execute(sql, tuple(data.values())):
print('Successful')
db.commit()
except:
print('Failed')
db.rollback()
db.close()
5、更新数据
import pymysql
data = {
'id': '20120001',
'name': 'Bob',
'age': 20
}
table = 'students'
keys = ', '.join(data.keys())
values = ', '.join(['%s'] * len(data))
db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
cursor = db.cursor()
sql = 'UPDATE students SET age = %s WHERE name = %s'
try:
cursor.execute(sql, (25, 'Bob'))
db.commit()
except:
db.rollback()
db.close()
6、更新数据(去重)
import pymysql
data = {
'id': '20120001',
'name': 'Bob',
'age': 21
}
table = 'students'
keys = ', '.join(data.keys())
values = ', '.join(['%s'] * len(data))
db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
cursor = db.cursor()
#SQL语句 ON DUPLICATE KEY UPDATE表示如果主键已经存在就执行更新操作i
#sql的值为 INSERT INTO students(id, name, age) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE
sql = 'INSERT INTO {table}({keys}) VALUES ({values}) ON DUPLICATE KEY UPDATE'.format(table=table, keys=keys,
values=values)
update = ','.join([" {key} = %s".format(key=key) for key in data])
#sql的值更新为INSERT INTO students(id, name, age) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE id = %s, name = %s, age = %s
sql += update
try:
if cursor.execute(sql, tuple(data.values()) * 2):
print('Successful')
db.commit()
except:
print('Failed')
db.rollback()
db.close()
7、删除数据
import pymysql
table = 'students'
condition = 'age > 20'
db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
cursor = db.cursor()
sql = 'DELETE FROM {table} WHERE {condition}'.format(table=table, condition=condition)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
8、查询数据
import pymysql
sql = 'SELECT * FROM students WHERE age >= 20'
db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spiders')
cursor = db.cursor()
try:
cursor.execute(sql)
#输出长度
print('Count:', cursor.rowcount)
#获取结果的第一条数据
data = cursor.fetchall()
print(data)
except:
print('Error')
mysql_connect.close()
mysql_cursor.close()
内容总结
以上是互联网集市为您收集整理的使用Python连接MySQL全部内容,希望文章能够帮你解决使用Python连接MySQL所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。