码迷,mamicode.com
首页 > 数据库 > 详细

python 连接数据库

时间:2019-04-18 21:44:25      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:utf8   port   nta   cell   inf   ace   UNC   结果   cin   

1.下载安装connector/python

地址:https://dev.mysql.com/downloads/connector/python/

下载的版本(mysql-connector-python-8.0.15-py3.5-windows-x86-64bit.msi)  下载后根据提示安装

 

2.数据库中数据

技术图片

 

3.使用python中的mysql.connector模块操作mysql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import mysql.connector                
 
# mysql1.py
config = {
    ‘host‘‘127.0.0.1‘,
    ‘user‘‘root‘,
    ‘password‘‘root‘,
    ‘port‘3306,
    ‘database‘‘test‘,
    ‘charset‘‘utf8‘
}
try:
    cnn = mysql.connector.connect(**config)
except mysql.connector.Error as e:
    print(‘connect fails!{}‘.format(e))
cursor = cnn.cursor()
try:
    sql_query = ‘select name,age from stu ;‘
    cursor.execute(sql_query)
    for name, age in cursor:
        print (name, age)
except mysql.connector.Error as e:
    print(‘query error!{}‘.format(e))
finally:
    cursor.close()
    cnn.close()

 

结果:

1
2
3
4
5
6
(u‘xiaoming‘10)
(u‘rose‘18)
(u‘jack‘19)
(u‘fang‘20)
(u‘Liang‘40)
(u‘Age‘None)

  

python 连接数据库

标签:utf8   port   nta   cell   inf   ace   UNC   结果   cin   

原文地址:https://www.cnblogs.com/dpqq/p/10732466.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!