使用Python創建MySQL數據庫實現字段動態添加以及動態的插入數據


應用場景:

我們須要設計一個數據庫來保存多個文檔中每一個文檔的keyword。

假如我們每一個文檔字符都超過了1000,取當中出現頻率最大的為我們的keyword。

如果每個文檔的keyword都超過了300,每個文件的0-299號存儲的是我們的keyword。那我們要建這樣一個數據庫。手動輸入這種一個表是不現實的。我們僅僅有通過程序來幫我實現這個反復枯燥的操作。


詳細的示意圖例如以下所看到的:

首先圖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()

    

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

最后就能夠得到我們的結果,例如以下圖所看到的:


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



參考文獻:

http://www.cnblogs.com/rollenholt/archive/2012/05/29/2524327.html

http://www.blogjava.net/alpha/archive/2007/07/23/131912.html

http://database.51cto.com/art/200811/97974_all.htm

感謝樓上幾位博主的無私奉獻精神。博主是在沒有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')
password輸入你自己數據庫中設置的。


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和本文中參數設置是一樣的。












轉載請注明出處,http://blog.csdn.net/chichoxian/article/details/38224361,謝謝合作^^













免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM