您的位置:首页 > 编程语言 > Python开发

【python学习】操作mysql

2016-04-08 11:32 411 查看
1、首先你得有一个mysql软件
[root@localhost mysql_test]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 14
Server 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 its
affiliates. Other names may be trademarks of their respective
owners.

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.rowcount
1
# 提交事务:
>>> 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
[root@localhost mysql_test]# cat conn_mysql.py
#!/usr/bin/python2.6

import mysql.connector
from datetime import datetime
import random

##id 根据时间判断
sid = datetime.now().strftime('%H:%M:%S').split(':')[1]+datetime.now().strftime('%H:%M:%S').split(':')[2]
##name 根据字符串,随即一个字符作为name
sname = random.choice('abcdefghijk')

conn = mysql.connector.connect(user='root', password='Wdl@163.com', 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 values

cursor.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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql python