python在sql添加数据库_使用Python创建MySQL数据库实现字段动态增加以及动态的插入数据...
應用場景:
我們需要設計一個數(shù)據庫來保存多個文檔中每個文檔的關鍵字。假如我們每個文檔字符都超過了1000,取其中出現(xiàn)頻率最大的為我們的關鍵字。
假設每個文檔的關鍵字都超過了300,每一個文件的0-299號存儲的是我們的關鍵字。那我們要建這樣一個數(shù)據庫,手動輸入這樣的一個表是不現(xiàn)實的,我們只有通過程序來幫我實現(xiàn)這個重復枯燥的操作。
具體的示意圖如下所示:
首先圖1是我們的原始表格:
圖1
這個時候我們需要程序來幫我們完成自動字段的創(chuàng)建和數(shù)據的插入。
圖2
上圖是我們整個表的概況。下面我們就用程序來總結出這樣的一個表格是怎么實現(xiàn)的。
'''
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()
記住最后一定要記得最后三行這個語句,否則你的操作不會寫入到數(shù)據庫中。
最后就可以得到我們的結果,如下圖所示:
程序的大體實現(xiàn)就是這樣。
參考文獻:
感謝樓上幾位博主的無私奉獻精神,博主是在沒有MySQL 的基礎上參照這些blog實現(xiàn)的。如有什么地方不足歡迎提出
批評和建議。對你的意見我在此表示由衷的感謝。
彩蛋:
1.操作數(shù)據庫出現(xiàn)的一些錯誤總結
如果你長時間為隊數(shù)據庫進行操作,再次進行操作的時候可能會出現(xiàn)以下錯誤:
raise errorclass, errorvalue
OperationalError: (2006, ‘MySQL server has gone away‘)
這個時候對于MySQL server 你要做的就是執(zhí)行一下下面這個命令
connect your_database
對于在python中的IDLE你需要執(zhí)行:
conn = MySQLdb.connect(host = 'localhost', port = 3306, user = 'root', passwd = '****')
curs = conn.cursor()
conn.select_db('addtest')密碼輸入你自己數(shù)據庫中設置的。
2UnicodeEncodeError: ‘latin-1‘ codec can‘t encode characters in position
出現(xiàn)上述這個錯誤的時候可以采用下面這個方法就可以解決。
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和本文中參數(shù)設置是一樣的。
原文:http://blog.csdn.net/chichoxian/article/details/38224361
總結
以上是生活随笔為你收集整理的python在sql添加数据库_使用Python创建MySQL数据库实现字段动态增加以及动态的插入数据...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在将沥青放入马歇尔实验仪时,为什么将其浸
- 下一篇: 种族制度是印度的特产吗?