duanguan1573 2014-05-14 03:35
浏览 27
已采纳

调用mysql并打印匹配文本文件的数据(python)

I know to connect to a db and connected it and i done it by

import MySQLdb

db = MySQLdb.connect(host="localhost", # your host, usually localhost
                     user="root", # your username
                      passwd="mysql", # your password
                      db="sakila") # name of the data base

I have a text file qwer.txt i have the table name:vehicle

I need to perform the operation which is to print words that match the text file and database.my operation for a small db and small file is given by this but what about connecting the database and matching them?

    mysql_row = "car,bike"
    file_str = "I have a car"

    mysql_elements = mysql_row.split(",")
    file_elements = file_str.split(" ")

    output_array = []

    for m_element in mysql_elements:
        for i in range(len(file_elements)):
            if ((m_element == file_elements[i]) and (i < len(file_elements)-1)):
               output_array.append(file_elements[i])

    print output_array  

Output:car

So,what are the changes to be done for connecting the database directly and the filename to perform the matching operation.

  • 写回答

1条回答 默认 最新

  • duanao6704 2014-05-14 03:54
    关注
    cursor = db.cursor()
    
    # execute SQL select statement
    cursor.execute("SELECT name FROM Vehicle")
    
    # commit your changes
    db.commit()
    
    keywords=[]
    

    here fetchall() gets all the rows and we append carnames to key words

    for i in cursor.fetchall():
        keywords.append(i[0])
    
    with open('qwer.txt','r') as file:
    

    this is used to open a file

        for line in file:
            for key in keywords:
                if key in line:
                    print line
    

    for each word in keywords search the line brings our output

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM