相关文章推荐
谦虚好学的口罩  ·  WindowChrome 类 ...·  1 年前    · 
魁梧的小蝌蚪  ·  Index of ...·  1 年前    · 

pycharm操作MySQL

在python3中,主要借助pymysql进行MySQL操作,简单记录下基本的操作步骤:
操作流程一般分为3步:
1. 建立数据库连接;
2. 执行操作(查询、插入、更新、删除等)
3. 关闭连接

这里直接贴代码了,用函数的形式进行表述了:

import pymysql
# 数据库连接
def connect():
    conn = pymysql.connect(host='localhost',
                           port=3306,
                           user='root',
                           password='root',
                           database='njust',
                           charset='utf8')
    # 获取操作游标
    cursor = conn.cursor()
    return {"conn": conn, "cursor": cursor

在执行操作时,借助游标方法: cursor.execute() 执行SQL操作。

# 1、查询操作并打印结果
def select_sql(table):
    connection = connect()
    conn, cursor = connection['conn'], connection['cursor']
    sql = "select * from %s" % table
    try:
        cursor.execute(sql)
        results = cursor.fetchall()
        print(results)
    except Exception as e:
        raise e
    finally:
        cursor.close()
        conn.close()
# 插入操作
def insert_sql(persons_values):
    connection = connect()
    conn, cursor = connection['conn'], connection['cursor']
    keys = ", ".join(persons_values.keys())
    qmark = ", ".join(["%s"] * len(persons_values))
    sql_insert = "insert into persons(%s) values (%s)" % (keys, qmark)
    print(sql_insert)
    try:
        cursor.execute(sql_insert, list(persons_values.values()))
        conn.commit()
        print("插入成功")
    except Exception as e:
        print(e)
        conn.rollback()
        print("插入失败")
    finally:
        cursor.close()
        conn.close()
# 利用字典进行插入
def insert_sql2(message):
    connection = connect()
    conn, cursor = connection['conn'], connection['cursor']
    sql_insert = "insert into persons(ID, LastName, FirstName) " \
                 "values (%(ID)s, %(LastName)s, %(FirstName)s)"
    try:
        cursor.execute(sql_insert, message)
        conn.commit()
        print("插入成功")
    except Exception as e:
        print(e)
        conn.rollback()
        print("插入失败")
    finally:
        cursor.close()
        conn.close()
# 更新数据库
def update_sql():
    connection = connect()
    conn, cursor = connection['conn'], connection['cursor']
    sql_update = "update persons set birthday=%s where ID=%s"
    try:
        cursor.execute(sql_update, ('2001/7/5', 3))
        conn.commit()
        print('更新成功')
    except Exception as e:
        print('更新失败', e)
        conn.rollback()
    finally:
        cursor.close()
        conn.close()
# 删除操作
def delete_sql(lastname):
    connection = connect()
    conn, cursor = connection['conn'], connection['cursor']
    sql_delete = "delete from persons where LastName=%s"
    try:
        cursor.execute(sql_delete, lastname)
        conn.commit()
        print('删除成功')
    except Exception as e:
        print('删除失败', e)
        conn.rollback()
    finally:
        cursor.close()
        conn.close()

SQL语句编写(占位符的应用)

执行的关键还是在SQL语句的编写。这类有几种方式:

  • 完整的SQL语句,直接调用
sql_select = "select * from tablename"
cursor.execute(sql_select)
  • 利用占位符传递参数。这里要注意,无论整数、字符串,占位符都为 %s,且不需加引号
    • 在sql语句中借助占位符,组成完整SQL
    tabel = 'persons'
    sql = "select * from %s" % table
    cursor.execute(sql)
      
    • 参数替代
    tabel = 'persons'
    sql = "select * from %s" 
    cursor.execute(sql, table)
    # 参数多于1个时,execute()传入参数应为list或者tuple类型
    sql_update = "update persons set birthday=%s where ID=%s"
    cursor.execute(sql_update, ('2001/7/5', 3))
      
    • 字典类型传递变量,这里要保证占位符的keys要包含在传递的字典keys中
    # 这里的占位符%s修改为%(字典keyname)s
    sql_insert = "insert into persons(ID, LastName, FirstName) " \
                 "values (%(ID)s, %(LastName)s, %(FirstName)s)"
    message = {
        "ID": 7,
        "LastName": "Jone",
        "FirstName": "Bob",
    cursor.execute(sql_insert, message)    
    

    参考来源:
    python3操作MySQL数据库
    Python连接MySQL数据库执行sql语句时的参数问题

    文章目录pycharm操作MySQLSQL语句编写(占位符的应用)pycharm操作MySQL在python3中,主要借助pymysql进行MySQL操作,简单记录下基本的操作步骤:操作流程一般分为3步:1. 建立数据库连接;2. 执行操作(查询、插入、更新、删除等)3. 关闭连接这里直接贴代码了,用函数的形式进行表述了:import pymysql# 数据库连接def c... 2.链接数据库 conn = pymysql.connect(host='127.0.01',port=3306,\nuser='root',password='123456') 3.获取游标 cursor=conn.cursor() 4.创建数据库和表 4.1 创建database cursor.execute('CREATE database if not exists duanzi') 4.2 创建table cursor.execute('CR
    python3.6使用pymysql连接Mysql数据库及简单的增删改查操作,供大家参考,具体内容如下 折腾好半天的数据库连接,由于之前未安装pip ,而且自己用的Python 版本为3.6. 只能用 pymysql 来连接数据库,(如果有和我一样未安装 pip 的朋友请 点这里windows下python安装pip简易教程),下边简单介绍一下连接的过程,以及简单的增删改查操作。 1.通过pip 安装pymysql 进入 cmd  输入  pip install pymysql  回车等待安装完成; 安装完成后出现如图相关信息,表示安装成功。 2.测试连接 import pymysql 
    pwd = input('请输入密码:') # 1.连接 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123', db='t1', charset='utf8') print(conn) # 2.创建游标 cursor = conn.cursor() #注意%s 主要记录关于sql中用占位符和上传image字段的方法, 下为按钮单击后执行插入信息事件部分代码记录,其中‘self.m_filePicker1.GetPath()’是其他部分代码取到的图片物理路径全名。 def upLoad(self, event): # 只读打开图片 f = open(self.m_filePicker1.GetPath(), "rb") data = f.read() # 返回文件信息
    1.使用tuple传参 select * from table where date in {}.format(tuple(XX)) 当tuple中只有一个参数时,因为tuple的特性其值为(XX,)会引起报错,如果为多个参数则可以正常运行。 2.使用string传参 select * from table where date in ({ }).format(" string “) 需要提前对字符串进行处理,得到格式为” ‘a’,‘b’ “的形式。 可以还用 ', '.join(” ‘{0}’
    在往数据库更新数据时,想要对多个字段进行批量更新。 我们知道,pymysql批量更新是使用executemany(sql,data)。 当想对多个字段进行批量更新,自然而然想到用这样的形式。 data = [['字段1',123,'admin'],['字段2',234,'admin']] sql = 'update user_table set %s=%s where username =%s' cur.executemany(sql,data) 这样写报错。
    目录起步查获取结果fetchone情况一情况二情况三fetchmany情况一情况二情况三fetchall情况一情况二情况三scroll移动相对移动绝对移动示例代码 #!/usr/bin/python3 # -*- coding: utf-8 -*- """pymysql查询 import pymysql conn = pymysql.connect( user='roo...
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='user1', password='123456', database='db1',charset='utf8') cursor = conn.cursor() sql = "SELECT * FROM students;" cursor.execute(sql) col = cursor.description fields = [] for i in range(len(col)): with connection.cursor() as cursor: # SQL 插入语句 sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" # 执行 SQL 插入语句,其中 %s 是占位符 cursor.execute(sql, ('user@example.com', 'password123')) # 提交事务 connection.commit() finally: # 关闭数据库连接 connection.close() 代码中首先使用 pymysql 模块的 `connect()` 方法连接本地的 MySQL 数据库,并指定了要访问的数据库名称、用户名、密码、字符集和游标类型。然后使用 `with` 关键字打开一个数据库游标,使用 `execute()` 方法执行一个 SQL 插入语句,其中使用 %s 占位符表示待插入数据的值。最后使用 `commit()` 方法提交事务并关闭数据库连接。 注意:示例中的代码只是提供了一个基本的示例,实际使用中可能需要考虑更多的因素,比如异常处理、数据类型转换等。