Python连接mysql【pymysql】

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pymysql
from datetime import datetime

try:
    conn = pymysql.connect(
        host = '127.0.0.1',
        user = 'root',
        password = 'root',
        db = 'news',
        port = 3306,
        charset = 'utf8'
    )

    # 创建一个连接
    cursor = conn.cursor()
    # 执行查询
    cursor.execute('select * from news order by created_at desc;')
    rest = cursor.fetchone()
    print(rest)
    # 插入
    insert_sql = "insert into news(title, content, created_at, types, image, author) values ('标题','内容',now(),'推荐','/static/img/news/03.png','Sakura')"
    print(insert_sql)
    rest = cursor.execute(insert_sql)
    print(rest)
    cursor.close()
    conn.close()

except pymysql.Error as e:
    print("Error: %s" % e)

你可能感兴趣的:(Python)