1、首先你得有一个mysql软件
[[email protected] 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
[[email protected] 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=‘[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 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)
时间: 2024-10-01 02:23:01