python3.7连接mysql数据及常用操作

Python 1136 0 2018-12-27

python3.7连接mysql数据及常用操作

以下是整理常用的python对mysql数据操作,代码如下:

import mysql.connector

"""连接数据库"""
mydb = mysql.connector.connect(
  host="localhost",       # 数据库主机地址
  user="root",    # 数据库用户名
  passwd="123456",   # 数据库密码
  database="python"  #数据库名
)

mycursor = mydb.cursor()

"""创建数据库python
mycursor.execute("CREATE DATABASE python")
"""

"""创建表sites
mycursor.execute("CREATE TABLE sites (name VARCHAR(255), url VARCHAR(255))")
"""

"""查看数据表
mycursor.execute("SHOW TABLES")
 
for x in mycursor:
  print(x)
"""

"""单条添加数据
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = ("哈喽吧", "http://www.hilo8.com")
mycursor.execute(sql, val)
mydb.commit()    # 数据表内容有更新,必须使用到该语句
print(mycursor.rowcount, "记录插入成功。")
"""

"""批量添加数据
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = [
  ('Google', 'https://www.google.com'),
  ('Github', 'https://www.github.com'),
  ('Taobao', 'https://www.taobao.com')
]
mycursor.executemany(sql, val)
mydb.commit()    # 数据表内容有更新,必须使用到该语句
print(mycursor.rowcount, "记录插入成功。")
"""

"""查询数据
mycursor.execute("SELECT * FROM sites")
myresult = mycursor.fetchall()     # fetchall() 获取所有记录
for x in myresult:
  print(x)
"""

"""删除数据
sql = "DELETE FROM sites WHERE name = 'Taobao'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, " 条记录删除")
"""

"""更新数据
sql = "UPDATE sites SET name = 'TB' WHERE name = 'Taobao'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, " 条记录被修改")
"""

详细可以再参考教程:http://www.runoob.com/python3/python-mysql-connector.html

上一篇:Python实例:判断输入的年份是否为闰年

下一篇:Python3.7解决没有Scripts文件夹及安装pip和pyqt5

讨论数量:0

请先登录再发表讨论。 2024-04-26

天涯网魂
3 杠 5 星
TA 的文章
TA 的随言
TA 的资源链