Python 連接數據庫

用Python來編寫網站,必須要能夠通過python操作數據庫,所謂操作數據庫,就是通過python實現對數據的連接,以及對記錄、字段的各種操作。

安裝python-MySQLdb

要想通過python來操作數據庫,還需要在已經安裝了mysql的基礎上安裝一個稱之爲mysqldb的庫,它是一個接口程序,python通過它對mysql數據實現各種操作。

在編程中,會遇到很多類似的接口程序,通過接口程序對另外一個對象進行操作,比較簡單。

這裏下載python-mysqldb:https://pypi.python.org/pypi/MySQL-python/

下載之後就可以安裝了。

我這裏只能演示ubuntu下安裝的過程。

sudo apt-get install  python-mysqldb

在shell中輸入上面的命令行,就安裝了。
不管什麼系統,安裝不是難題。安裝之後,怎麼知道安裝的結果呢?

>>> import MySQLdb 

在python的交互模式中,輸入上面的指令,如果不報錯,恭喜你,已經安裝好了。如果報錯,恭喜你,可以藉着錯誤信息提高自己的計算機水平了,請求助於google大神。

交互模式下操作數據庫之連接數據庫

操作數據庫的前提是先有數據庫。

先建立一個數據庫。

$ mysql -u root -p
Enter password:                             

打開數據庫,正確輸入密碼之後,呈現下面的結果

Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 5.7.24-0ubuntu0.18.04.1 (Ubuntu)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

在這個狀態下,輸入如下命令,建立一個數據庫:

mysql> create database mytest character set utf8;
Query OK, 1 row affected (0.00 sec)

注意上面的指令,如果僅僅輸入:create database mytest,也可以,但是,我在後面增加了character set utf8,意思是所建立的數據庫mytest,編碼是utf-8的,這樣存入漢字就不是亂碼了。

看到那一行提示:Query OK, 1 row affected (0.00 sec),就說明這個數據庫已經建立好了,名字叫做:mytest

數據庫建立之後,就可以用python通過已經安裝的mysqldb來連接這個名字叫做mytest的庫了。進入到python交互模式。

>>> import MySQLdb
>>> conn = MySQLdb.connect(host="localhost",user="root",passwd="123123",db="mytest",port=3306,charset="utf8")

逐個解釋上述命令的含義:

  • host:等號的後面應該填寫mysql數據庫的地址,因爲就數據庫就在本機上(也稱作本地),所以使用localhost,注意引號。如果在其它的服務器上,這裏應該填寫ip地址。一般中小型的網站,數據庫和程序都是在同一臺服務器(計算機)上,就使用localhost了。
  • user:登錄數據庫的用戶名,這裏一般填寫"root",還是要注意引號。當然,如果是比較大型的服務,數據庫會提供不同的用戶,那時候可以更改爲相應用戶。但是,不同用戶的權限可能不同,所以,在程序中,如果要操作數據庫,還要注意所擁有的權限。在這裏用root,就放心了,什麼權限都有啦。不過,這樣做,在大型系統中是應該避免的。
  • passwd:上述user賬戶對應的登錄mysql的密碼。我在上面的例子中用的密碼是"123123"。不要忘記引號。
  • db:就是剛剛通create命令建立的數據庫,我建立的數據庫名字是"mytest",還是要注意引號。看官如果建立的數據庫名字不是這個,就寫自己所建數據庫名字。
  • port:一般情況,mysql的默認端口是3306,當mysql被安裝到服務器之後,爲了能夠允許網絡訪問,服務器(計算機)要提供一個訪問端口給它。
  • charset:這個設置,在很多教程中都不寫,結果在真正進行數據存儲的時候,發現有亂碼。這裏我將qiwsirtest這個數據庫的編碼設置爲utf-8格式,這樣就允許存入漢字而無亂碼了。注意,在mysql設置中,utf-8寫成utf8,沒有中間的橫線。但是在python文件開頭和其它地方設置編碼格式的時候,要寫成utf-8。切記!

注:connect中的host、user、passwd等可以不寫,只有在寫的時候按照host、user、passwd、db(可以不寫)、port順序寫就可以,注意端口號port=3306還是不要省略的爲好,如果沒有db在port前面,直接寫3306會報錯.

其實,關於connect的參數還不少,下面摘抄來自mysqldb官方文檔的內容,把所有的參數都列出來,還有相關說明,請看官認真閱讀。不過,上面幾個是常用的,其它的看情況使用。

connect(parameters...)

Constructor for creating a connection to the database. Returns a Connection Object. Parameters are the same as for the MySQL C API. In addition, there are a few additional keywords that correspond to what you would pass mysql_options() before connecting. Note that some parameters must be specified as keyword arguments! The default value for each parameter is NULL or zero, as appropriate. Consult the MySQL documentation for more details. The important parameters are:

  • host: name of host to connect to. Default: use the local host via a UNIX socket (where applicable)
  • user: user to authenticate as. Default: current effective user.
  • passwd: password to authenticate with. Default: no password.
  • db: database to use. Default: no default database.
  • port: TCP port of MySQL server. Default: standard port (3306).
  • unix_socket: location of UNIX socket. Default: use default location or TCP for remote hosts.
  • conv: type conversion dictionary. Default: a copy of MySQLdb.converters.conversions
  • compress: Enable protocol compression. Default: no compression.
  • connect_timeout: Abort if connect is not completed within given number of seconds. Default: no timeout (?)
  • named_pipe: Use a named pipe (Windows). Default: don't.
  • init_command: Initial command to issue to server upon connection. Default: Nothing.
  • read_default_file: MySQL configuration file to read; see the MySQL documentation for mysql_options().
  • read_default_group: Default group to read; see the MySQL documentation for mysql_options().
  • cursorclass: cursor class that cursor() uses, unless overridden. Default: MySQLdb.cursors.Cursor. This must be a keyword parameter.
  • use_unicode: If True, CHAR and VARCHAR and TEXT columns are returned as Unicode strings, using the configured character set. It is best to set the default encoding in the server configuration, or client configuration (read with read_default_file). If you change the character set after connecting (MySQL-4.1 and later), you'll need to put the correct character set name in connection.charset.

If False, text-like columns are returned as normal strings, but you can always write Unicode strings.

This must be a keyword parameter.

  • charset: If present, the connection character set will be changed to this character set, if they are not equal. Support for changing the character set requires MySQL-4.1 and later server; if the server is too old, UnsupportedError will be raised. This option implies use_unicode=True, but you can override this with use_unicode=False, though you probably shouldn't.

If not present, the default character set is used.

This must be a keyword parameter.

  • sql_mode: If present, the session SQL mode will be set to the given string. For more information on sql_mode, see the MySQL documentation. Only available for 4.1 and newer servers.

If not present, the session SQL mode will be unchanged.

This must be a keyword parameter.

  • ssl: This parameter takes a dictionary or mapping, where the keys are parameter names used by the mysql_ssl_set MySQL C API call. If this is set, it initiates an SSL connection to the server; if there is no SSL support in the client, an exception is raised. This must be a keyword parameter.

我已經完成了數據庫的連接,雖然是在交互模式下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章