Python 连接pymysql 并读入一个文件夹所有照片的路径存储到sql中

一、 安装mysql
1、 下载地址:
链接:https://pan.baidu.com/s/1vWHuZUJHdZzECFMrUE_rvA 密码:7lrn
将其解压(随便放在哪个盘),然后你会发现有以下几个文件(除了data文件)
这里写图片描述
进入bin 文件夹,以管理员身份运行cmd,在其中输入mysqld --install ,如不以管理员身份,则报错:

Install/Remove of the Service Denied!

有很对blog 说要配置.ini文件,其实不用。下来一步是:在cmd输入:mysqld --initialize --insecure --user ==mysql 这一步时间有点长,会在你解压包下,生成一个data文件。注意加上—insecure不会生成一个随机密码,也就是登陆sql的时候,只需回车。
如果想修改root 密码,则在cmd中输入:

update user set password=password("123456") where user="root";(别忘了最后加分号)

下一步:启动sql。net start mysql
下一步:登陆sql。mysql -u root -p
二、 python 调用
安装Pymysql 库

db = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='testdb')

host:mysql是服务器地址,user 就是用户,passwd:是你自己的密码 db 是数据库,这个在连接前,你需要进入bin文件下命令行,登陆sql,输入create database if not exists testdb defult charset utf8;
自己写了个读入一个文件下所有jpg文件的路径并存储到sql,代码如下(注释的地方注意):

# -*- coding: utf-8 -*-
##得到图像路径并保存在sql中
import pymysql
import os
import re
try:
    db = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='testdb')
    db.autocommit(True)
    cursor=db.cursor()
    '''创建表'''
    sql=""" create table if not exists path(id int,p varchar(100)) engine=innodb charset utf8"""
    cursor.execute(sql)
    i=1
    for path,dirpath ,file in os.walk(r"C:\Users\Y\Desktop\demo1"):
        for f in file:
            r1=r'(jpg)'
            if re.findall(r1,f):
                path=path.replace("\\","||")#笔者实验路径的delimiter是 \\ 的话,存到sql中会把\\去掉
                insert="insert into path(id,p) values({},'{}')".format(i,path+"||"+f)
                # 注意第二个{}要加上'{}'
                cursor.execute(insert)
                i+=1
    cursor.execute("select * from path")
    rows=cursor.fetchall()
    for r in rows:
        print(r)
    print("complete!!!!")
except:
    print("连接失败")

猜你喜欢

转载自blog.csdn.net/qq_15642411/article/details/80499654
今日推荐