python中操作mysql

在python操作mysql

  1. 安装: pip install pymysql

  2. 使用

    import pymysql
     
    db = pymysql.connect(host='localhost', # ip
                         user='user',  # 用户
                         password='passwd',  # 密码
                         db='db',  # 要操作的库
                         charset='utf8')
    
    try:
        with db.cursor() as cursor:
            # 插入
            sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
            cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
        # 需要手动提交才会执行
        db.commit()
    
        with db.cursor() as cursor:
            # 读取记录
            sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
            cursor.execute(sql, ('webmaster@python.org',))
            result = cursor.fetchone()
            print(result)
    finally:
        db.close()
    
posted @ 2020-09-18 12:49  zeeyan  阅读(109)  评论(0)    收藏  举报