標籤:python mysql
1、首先你得有一個mysql軟體
[[email protected] mysql_test]# mysql -u root -pEnter password: Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 14Server version: 5.7.11 MySQL Community Server (GPL)Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.Type ‘help;‘ or ‘\h‘ for help. Type ‘\c‘ to clear the current input statement.mysql> show databases;+--------------------+| Database |+--------------------+| information_schema || falcon || mysql || performance_schema || pydb || sys |+--------------------+6 rows in set (0.05 sec)mysql>
2、需要mysql驅動
mysql-connector-python:是MySQL官方的純Python驅動;
>>> import mysql.connector>>>
練習一下
# 匯入MySQL驅動:>>> import mysql.connector# 注意把password設為你的root口令:>>> conn = mysql.connector.connect(user=‘root‘, password=‘password‘, database=‘test‘, use_unicode=True)>>> cursor = conn.cursor()# 建立user表:>>> cursor.execute(‘create table user (id varchar(20) primary key, name varchar(20))‘)# 插入一行記錄,注意MySQL的預留位置是%s:>>> cursor.execute(‘insert into user (id, name) values (%s, %s)‘, [‘1‘, ‘Michael‘])>>> cursor.rowcount1# 提交事務:>>> conn.commit()>>> cursor.close()# 執行查詢:>>> cursor = conn.cursor()>>> cursor.execute(‘select * from user where id = %s‘, (‘1‘,))>>> values = cursor.fetchall()>>> values[(u‘1‘, u‘Michael‘)]# 關閉Cursor和Connection:>>> cursor.close()True>>> conn.close()
3、寫一個conn_mysql.py
[[email protected] mysql_test]# cat conn_mysql.py#!/usr/bin/python2.6import mysql.connectorfrom datetime import datetimeimport random##id 根據時間判斷sid = datetime.now().strftime(‘%H:%M:%S‘).split(‘:‘)[1]+datetime.now().strftime(‘%H:%M:%S‘).split(‘:‘)[2]##name 根據字串,隨即一個字元作為namesname = random.choice(‘abcdefghijk‘)conn = mysql.connector.connect(user=‘root‘, password=‘[email protected]‘, database=‘pydb‘, use_unicode=True)cursor = conn.cursor()#cursor.execute(‘create table user (id varchar(20) primary key, name varchar(20))‘)cursor.execute(‘insert into user (id, name) values (%s, %s)‘, [sid, sname])conn.commit()cursor.close()cursor = conn.cursor()cursor.execute(‘select * from user‘)values = cursor.fetchall()print valuescursor.close()conn.close()
4、查詢mysql
mysql> select * from user;+------+---------+| id | name |+------+---------+| 1 | Michael || 1908 | a || 1916 | k || 1928 | h || 2 | Kate |+------+---------+5 rows in set (0.00 sec)
【python學習】操作mysql