1. 程式人生 > >使用Python建立MySQL資料庫實現欄位動態增加以及動態的插入資料

使用Python建立MySQL資料庫實現欄位動態增加以及動態的插入資料

應用場景:

我們需要設計一個數據庫來儲存多個文件中每個文件的關鍵字。假如我們每個文件字元都超過了1000,取其中出現頻率最大的為我們的關鍵字。

假設每個文件的關鍵字都超過了300,每一個檔案的0-299號儲存的是我們的關鍵字。那我們要建這樣一個數據庫,手動輸入這樣的一個表是不現實的,我們只有通過程式來幫我實現這個重複枯燥的操作。

具體的示意圖如下所示:

首先圖1是我們的原始表格:

        

                                         圖1

這個時候我們需要程式來幫我們完成自動欄位的建立和資料的插入。

                  

                                                 圖2

上圖是我們整個表的概況。下面我們就用程式來總結出這樣的一個表格是怎麼實現的。

'''
function description : Add the fields and data dynamicly.

data : 2014-08-04

author : Chicho

running : python addfileds.py

'''

import MySQLdb
#connect the database
#the argvs based on the database you set.
#Generally speaking, you should change the No. of the port 3306 , because it's easy to be  attack
#localhost = 127.0.0.1
conn = MySQLdb.connect(host = 'localhost', port = 3306, user = 'root', passwd = '*****')
curs = conn.cursor()

# create a database named addtest
#Ensure the program can run multiple times,we should use try...exception
try:
    curs.execute('create database addtest')
except:
    print 'Database addtest exists!'

conn.select_db('addtest')

# create a table named addfields
try:
    curs.execute('create table addfields(id int PRIMARY KEY NOT NULL,name text)')
except:
    print('The table addfields exists!')


# add the fileds
try:
    for i in range(1):
        sql = "alter table addfields add key%s text" %i
        curs.execute(sql)
except Exception,e:
    print e


for i in range(4): #insert 5 lines
    sql = "insert into addfields set id=%s" %i
    curs.execute(sql)
    sql = "update addfields set name = 'hello%s' where id= %s"%(i,i)
    curs.execute(sql)
    for j in range(5):
        sql = "update addfields set key%s = 'world%s%s' where id=%s"%(j,i,j,i)
        curs.execute(sql)

#this is very important
conn.commit()
curs.close()
conn.close()

    

記住最後一定要記得最後三行這個語句,否則你的操作不會寫入到資料庫中。

最後就可以得到我們的結果,如下圖所示:


程式的大體實現就是這樣。

參考文獻:

感謝樓上幾位博主的無私奉獻精神,博主是在沒有MySQL 的基礎上參照這些blog實現的。如有什麼地方不足歡迎提出

批評和建議。對你的意見我在此表示由衷的感謝。

彩蛋:

1.操作資料庫出現的一些錯誤總結

如果你長時間為隊資料庫進行操作,再次進行操作的時候可能會出現以下錯誤:

    raise errorclass, errorvalue
OperationalError: (2006, 'MySQL server has gone away')

這個時候對於MySQL server 你要做的就是執行一下下面這個命令

connect your_database

對於在python中的IDLE你需要執行:

conn = MySQLdb.connect(host = 'localhost', port = 3306, user = 'root', passwd = '****')
curs = conn.cursor()
conn.select_db('addtest')
密碼輸入你自己資料庫中設定的。

2.UnicodeEncodeError: 'latin-1' codec can't encode characters in position 

出現上述這個錯誤的時候可以採用下面這個方法就可以解決。
 conn.set_character_set('utf8')
    curs.execute('set names utf8')
    curs.execute('SET CHARACTER SET utf8;')
    curs.execute('SET character_set_connection=utf8;')
conn,curs和本文中引數設定是一樣的。