1、预备工作
首先确保自己已经安装了python3.4(本人是ubuntu14.04版的,自带了,安装的话:www.python.org),mysql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
[tian
@tian
][
23
:
22
:
55
][~]:~$ python3
Python
3.4
.
0
(
default
, Apr
11
2014
,
13
:
05
:
11
)
[GCC
4.8
.
2
] on linux
Type
"help"
,
"copyright"
,
"credits"
or
"license"
for
more information.
>>> exit()
[tian
@tian
][
23
:
23
:
17
][~]:~$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is
77
Server version:
5.5
.
41
-0ubuntu0.
14.04
.
1
(Ubuntu)
Copyright (c)
2000
,
2014
, 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>
|
2、下载python的mysql驱动
我用的方法是下载驱动包,然后自己安装的,网上有通过pip安装的,但是没有成功(好郁闷..)
A. http://dev.mysql.com/downloads/connector/python/ 通过网址,然后选择这个:
B.ftp地址:http://ftp.ntu.edu.tw/MySQL/Downloads/Connector-Python/ ,这里面有很多mysql相关的资源:
C.然后,命令安装即可!
1
2
3
|
tar xvf mysql-connector-python-
1.1
.
6
.tar.gz
cd mysql-connector-python-
1.1
.
6
sudo python3 setup.py install
|
3、运行,测试!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
[tian
@tian
][
23
:
16
:
55
][~]:~$ python3
Python
3.4
.
0
(
default
, Apr
11
2014
,
13
:
05
:
11
)
[GCC
4.8
.
2
] on linux
Type
"help"
,
"copyright"
,
"credits"
or
"license"
for
more information.
>>>
import
mysql.connector #导入python的mysql驱动包,如果没有报错的话,就说明安装成功了
>>> conn = mysql.connector.connect(user=
'root'
, password=
'root'
, database=
'test_python'
) #连接mysql
>>> cursor = conn.cursor() #获取链接
>>> cursor.execute(
'create table user (id varchar(20) primary key, name varchar(20))'
) #执行sql
>>> cursor.execute(
'insert into user (id, name) values (%s, %s)'
, [
'1'
,
'Michael'
]) #插入数据
>>> cursor.rowcount
1
>>> conn.commit()
>>> cursor.close()
True
>>> cursor = conn.cursor()
>>> cursor.execute(
'select * from user where id = %s'
, [
'1'
]) # 查询数据
>>> values = cursor.fetchall()
>>> values
[(
'1'
,
'Michael'
)]
>>> cursor.close()
True
>>> conn.close()
>>> exit()
|