zoukankan      html  css  js  c++  java
  • Python访问MySQL数据库

    # -*- coding: utf-8 -*-
    # Author: areful
    #
    # needs module 'mysql-connector-python', running command below to install it:
    # pip install mysql-connector-python
    #
    #
    # remote connect mysql(on Ubuntu18.04.1 64bit, MySQL5.7, ip=192.168.147.130, MySQL port 3306):
    # modify /etc/mysql/mysql.conf.d/mysqld.cnf:
    # from "bind-address = 127.0.0.1" to "#bind-address = 127.0.0.1"
    #
    # mysql> use mysql;
    # mysql> update user set authentication_string=password('新密码') where user='root';
    # mysql> flush privileges;
    # mysql> quit
    #
    # GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123456' WITH GRANT OPTION;
    #
    import mysql.connector
    
    conn = mysql.connector.connect(host='192.168.147.130', port='3306', database='test',
                                   user='root', password='123456', use_unicode=True)
    cursor = conn.cursor()
    # 创建user表:
    cursor.execute('CREATE TABLE IF NOT EXISTS user (id VARCHAR(20) PRIMARY KEY, name VARCHAR(20))')
    # 插入一行记录,注意MySQL的占位符是%s:
    cursor.execute('INSERT INTO user (id, name) VALUES (%s, %s)', ['1', 'Michael'])
    var = cursor.rowcount
    # 提交事务:
    conn.commit()
    cursor.close()
    # 运行查询:
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM user WHERE id = %s' % ('1',))
    values = cursor.fetchall()
    print(values)
    
    # 关闭Cursor和Connection:
    cursor.close()
    conn.close()
    

      

  • 相关阅读:
    多线程《三》进程与线程的区别
    多线程《二》开启线程的两种方式
    多线程《一》线程理论
    多进程《七》生产者消费者模型
    多进程《六》队列
    互斥锁与join
    多进程《五》互斥锁
    多进程《四》守护进程
    再度认识未来——2.11
    开始——2.10
  • 原文地址:https://www.cnblogs.com/areful/p/10369569.html
Copyright © 2011-2022 走看看