OSX下mysql、pymysql的安

发布时间:2019-10-10 09:17:06编辑:auto阅读(1782)

    OSX下mysql安装较为简单,mysql官网下载地址http://dev.mysql.com/downloads/mysql/
    选择OSX版本安装
    TIPS:默认新版mysql在OSX下的配置文件/etc/my.cnf不存在,其他默认路径下也没有,需自行添加。

    因python3支持问题,使用pymysql替代MySQLdb、mysqlclient-python连接数据库,github主页见
    https://github.com/PyMySQL/PyMySQL

    安装$ pip3 install PyMySQL
    使用方法示例

    CREATE TABLE `users` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `email` varchar(255) COLLATE utf8_bin NOT NULL,
        `password` varchar(255) COLLATE utf8_bin NOT NULL,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
    AUTO_INCREMENT=1 ;
    
    import pymysql.cursors
    connection = pymysql.connect(host='localhost',
                                 user='user',
                                 password='passwd',
                                 db='db',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
        with connection.cursor() as cursor:
            # Create a new record
            sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
            cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
    
        # connection is not autocommit by default. So you must commit to save
        # your changes.
        connection.commit()
    
        with connection.cursor() as cursor:
            # Read a single record
            sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
            cursor.execute(sql, ('webmaster@python.org',))
            result = cursor.fetchone()
            print(result)
    finally:
        connection.close()
    

关键字