python3.4连接mysql

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值