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

來源:互聯網
上載者:User

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

應用情境:

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

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


具體的如下所示:

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

        

                                         圖1

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

                  

                                                 圖2

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

'''function description : Add the fields and data dynamicly.data : 2014-08-04author : Chichorunning : 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.1conn = 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...exceptiontry:    curs.execute('create database addtest')except:    print 'Database addtest exists!'conn.select_db('addtest')# create a table named addfieldstry:    curs.execute('create table addfields(id int PRIMARY KEY NOT NULL,name text)')except:    print('The table addfields exists!')# add the filedstry:    for i in range(1):        sql = "alter table addfields add key%s text" %i        curs.execute(sql)except Exception,e:    print efor 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 importantconn.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')
密碼輸入你自己資料庫中設定的。


2UnicodeEncodeError: '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和本文中參數設定是一樣的。







Python串連MySQL建立資料庫建立表插入資料在程式裡面也可以查詢出來插入的資料,但是在資料庫裡表為空白

因為你插入資料沒有commit、在程式裡面也可以查詢出來插入的資料是從緩衝中查的。
 
mysql資料庫設定了一個id欄位是自增的,但是插入資料時還是要手動插入id,不插入id就會出錯

成功的執行例子如下,僅供參考.

mysql> CREATE TABLE test_create_tab2 (
-> id INT AUTO_INCREMENT,
-> val VARCHAR(10),
-> PRIMARY KEY (id)
-> );
Query OK, 0 rows affected (0.09 sec)

mysql> INSERT INTO test_create_tab2(val) VALUES ('NO id');
Query OK, 1 row affected (0.03 sec)

mysql> select last_insert_id() as id;
+----+
| id |
+----+
| 1 |
+----+
1 row in set (0.00 sec)

mysql> INSERT INTO test_create_tab2(val) VALUES ('NO id 2');
Query OK, 1 row affected (0.03 sec)

mysql> select last_insert_id() as id;
+----+
| id |
+----+
| 2 |
+----+
1 row in set (0.00 sec)

mysql> select * from test_create_tab2;
+----+---------+
| id | val |
+----+---------+
| 1 | NO id |
| 2 | NO id 2 |
+----+---------+
2 rows in set (0.00 sec)
 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.