mac anaconda python连接数据库

首次尝试anaconda python连接数据库,记录一下

1.  到相应python 版本环境下,下载相应数据库包,以下为命令行

source activate python3.5env #进入Python3.5环境下
conda install pymysql #下载mysql数据库交互包

2.import pymysql不报错

[anaconda 中 conda命令找不到mysql-python包 其他或许可尝试 pip install mysql-python   然后import MySQLdb]

3.数据库连接步骤:

(1)创建连接

(2)创建游标

(3)执行sql语句

try:
    conn = pymysql.connect(host='localhost', user='root', password='', db='test', port=3306, charset='utf8')

    #检验数据库连接是否成功
    my_cursor=conn.cursor()
    #执行sql语句,返回影响条数
    data = my_cursor.execute('select * from student')
    one = my_cursor.fetchone() #获取一条数据
    all = my_cursor.fetchall()
    print(data)
    print(one)
    print(all)
    print(my_cursor.description)#description属性,获取的是数据库每个栏位情况
    print(type(my_cursor.fetchone()))
    #将一行数据存储为字典
    new_list = dict(zip([x[0] for x in my_cursor.description],[x for x in one]))
    print(new_list)
except pymysql.Error as e:
    print(e)
    print('数据库操作失败')
finally:
    # 若数据库连接成功,则关闭数据库
    print('over')
    if conn:
        conn.close()

猜你喜欢

转载自blog.csdn.net/u013344884/article/details/81172093
今日推荐