国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development Python Tutorial 再Python程序中操作MySQL的基本方法

再Python程序中操作MySQL的基本方法

Jun 06, 2016 am 11:13 AM
mysql python

Python操作Mysql

最近在學(xué)習(xí)python,這種腳本語言毫無疑問的會(huì)跟數(shù)據(jù)庫產(chǎn)生關(guān)聯(lián),因此這里介紹一下如何使用python操作mysql數(shù)據(jù)庫。我python也是零基礎(chǔ)學(xué)起,所以本篇博客針對(duì)的是python初學(xué)者,大牛可以選擇繞道。

另外,本篇基于的環(huán)境是Ubuntu13.10,使用的python版本是2.7.5。
MYSQL數(shù)據(jù)庫

MYSQL是一個(gè)全球領(lǐng)先的開源數(shù)據(jù)庫管理系統(tǒng)。它是一個(gè)支持多用戶、多線程的數(shù)據(jù)庫管理系統(tǒng),與Apache、PHP、Linux共同組成LAMP平臺(tái),在web應(yīng)用中廣泛使用,例如Wikipedia和YouTube。MYSQL包含兩個(gè)版本:服務(wù)器系統(tǒng)和嵌入式系統(tǒng)。
環(huán)境配置

在我們開始語法學(xué)習(xí)之前,還需要按裝mysql和python對(duì)mysql操作的模塊。

安裝mysql:

sudo apt-get install mysql-server

安裝過程中會(huì)提示你輸入root帳號(hào)的密碼,符合密碼規(guī)范即可。

接下來,需要安裝python對(duì)mysql的操作模塊:

sudo apt-get install python-mysqldb

這里需要注意:安裝完python-mysqldb之后,我們默認(rèn)安裝了兩個(gè)python操作模塊,分別是支持C語言API的_mysql和支持Python API的MYSQLdb。稍后會(huì)重點(diǎn)講解MYSQLdb模塊的使用。

接下來,我們進(jìn)入MYSQL,創(chuàng)建一個(gè)測(cè)試數(shù)據(jù)庫叫testdb。創(chuàng)建命令為:

create database testdb;


然后,我們創(chuàng)建一個(gè)測(cè)試賬戶來操作這個(gè)testdb數(shù)據(jù)庫,創(chuàng)建和授權(quán)命令如下:

create user 'testuser'@'127.0.0.1' identified by 'test123';
grant all privileges on testdb.* to 'testuser'@'127.0.0.1';

_mysql module

_mysql模塊直接封裝了MYSQL的C語言API函數(shù),它與python標(biāo)準(zhǔn)的數(shù)據(jù)庫API接口是不兼容的。我更推薦大家使用面向?qū)ο蟮腗YSQLdb模塊才操作mysql,這里只給出一個(gè)使用_mysql模塊的例子,這個(gè)模塊不是我們學(xué)習(xí)的重點(diǎn),我們只需要了解有這個(gè)模塊就好了。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import _mysql
import sys

try:
  con = _mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb')
  con.query("SELECT VERSION()")
  result = con.use_result()

  print "MYSQL version : %s " % result.fetch_row()[0]

except _mysql.Error, e:
  print "Error %d: %s %s" % (e.args[0], e.args[1])
  sys.exit(1)

finally:
  if con:
    con.close()

這個(gè)代碼主要是獲取當(dāng)前mysql的版本,大家可以模擬敲一下這部分代碼然后運(yùn)行一下。
MYSQLdb module

MYSQLdb是在_mysql模塊的基礎(chǔ)上進(jìn)一步進(jìn)行封裝,并且與python標(biāo)準(zhǔn)數(shù)據(jù)庫API接口兼容,這使得代碼更容易被移植。Python更推薦使用這個(gè)MYSQLdb模塊來進(jìn)行MYSQL操作。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mysql

try:
  conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb')
  cur = conn.cursor()
  cur.execute("SELECT VERSION()")

  version = cur.fetchone()
  print "Database version : %s" % version

except mysql.Error, e:
  print "Error %d:%s" % (e.args[0], e.args[1])
  exit(1)

finally:
  if conn:
    conn.close()


我們導(dǎo)入了MySQLdb模塊并把它重命名為mysql,然后調(diào)用MySQLdb模塊的提供的API方法來操作數(shù)據(jù)庫。同樣也是獲取當(dāng)前主機(jī)的安裝的mysql版本號(hào)。
創(chuàng)建新表

接下來,我們通過MySQLdb模塊創(chuàng)建一個(gè)表,并在其中填充部分?jǐn)?shù)據(jù)。實(shí)現(xiàn)代碼如下:

#!/usr/bin/python

# -*- coding: utf-8 -*-

import MySQLdb as mysql

conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb');

with conn:
  cur = conn.cursor()
  cur.execute("DROP TABLE IF EXISTS writers");
  cur.execute("CREATE TABLE writers(id INT PRIMARY KEY AUTO_INCREMENT, name varchar(25))")
  cur.execute("insert into writers(name) values('wangzhengyi')")
  cur.execute("insert into writers(name) values('bululu')")
  cur.execute("insert into writers(name) values('chenshan')")

這里使用了with語句。with語句會(huì)執(zhí)行conn對(duì)象的enter()和__exit()方法,省去了自己寫try/catch/finally了。

執(zhí)行完成后,我們可以通過mysql-client客戶端查看是否插入成功,查詢語句:

select * from writers;

查詢結(jié)果如下:

2015729102658336.jpg (965×174)

查詢數(shù)據(jù)

剛才往表里插入了部分?jǐn)?shù)據(jù),接下來,我們從表中取出插入的數(shù)據(jù),代碼如下:

#!/usr/bin/python

import MySQLdb as mysql

conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb');

with conn:
  cursor = conn.cursor()
  cursor.execute("select * from writers")
  rows = cursor.fetchall()

  for row in rows:
    print row


查詢結(jié)果如下:

(1L, 'wangzhengyi')
(2L, 'bululu')
(3L, 'chenshan')

dictionary cursor

我們剛才不論是創(chuàng)建數(shù)據(jù)庫還是查詢數(shù)據(jù)庫,都用到了cursor。在MySQLdb模塊有許多種cursor類型,默認(rèn)的cursor是以元組的元組形式返回?cái)?shù)據(jù)的。當(dāng)我們使用dictionary cursor時(shí),數(shù)據(jù)是以python字典形式返回的。這樣我們就可以通過列名獲取查詢數(shù)據(jù)了。

還是剛才查詢數(shù)據(jù)的代碼,改為dictionary cursor只需要修改一行代碼即可,如下所示:

#!/usr/bin/python

import MySQLdb as mysql

conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb');

with conn:
  cursor = conn.cursor(mysql.cursors.DictCursor)
  cursor.execute("select * from writers")
  rows = cursor.fetchall()

  for row in rows:
    print "id is %s, name is %s" % (row['id'], row['name'])

使用dictionary cursor,查詢結(jié)果如下:

id is 1, name is wangzhengyi
id is 2, name is bululu
id is 3, name is chenshan


預(yù)編譯

之前寫過php的同學(xué)應(yīng)該對(duì)預(yù)編譯很了解,預(yù)編譯可以幫助我們防止sql注入等web攻擊還能幫助提高性能。當(dāng)然,python肯定也是支持預(yù)編譯的。預(yù)編譯的實(shí)現(xiàn)也比較簡(jiǎn)單,就是用%等占位符來替換真正的變量。例如查詢id為3的用戶的信息,使用預(yù)編譯的代碼如下:

#!/usr/bin/python

import MySQLdb as mysql

conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb');

with conn:
  cursor = conn.cursor(mysql.cursors.DictCursor)
  cursor.execute("select * from writers where id = %s", "3")
  rows = cursor.fetchone()
  print "id is %d, name is %s" % (rows['id'], rows['name'])

我這里使用了一個(gè)%s的占位符來替換“3”,代表需要傳入的是一個(gè)字符串類型。如果傳入的不是string類型,則會(huì)運(yùn)行報(bào)錯(cuò)。
事務(wù)

事務(wù)是指在一個(gè)或者多個(gè)數(shù)據(jù)庫中對(duì)數(shù)據(jù)的原子操作。在一個(gè)事務(wù)中,所有的SQL語句的影響要不就全部提交到數(shù)據(jù)庫,要不就全部都回滾。

對(duì)于支持事務(wù)機(jī)制的數(shù)據(jù)庫,python接口在創(chuàng)建cursor的時(shí)候就開始了一個(gè)事務(wù)。可以通過cursor對(duì)象的commit()方法來提交所有的改動(dòng),也可以使用cursor對(duì)象的rollback方法來回滾所有的改動(dòng)。

我這里寫一個(gè)代碼,對(duì)不存在的表進(jìn)行插入操作,當(dāng)拋出異常的時(shí)候,調(diào)用rollback進(jìn)行回滾,實(shí)現(xiàn)代碼如下:

#!/usr/bin/python

# -*- coding: utf-8 -*-

import MySQLdb as mysql


try:
  conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb');
  cur = conn.cursor()
  cur.execute("insert into writers(name) values('wangzhengyi4')")
  cur.execute("insert into writers(name) values('bululu5')")
  cur.execute("insert into writerss(name) values('chenshan6')")

  conn.commit()

except mysql.Error, e:
  if conn:
    conn.rollback()
    print "Error happens, rollback is call"

finally:
  if conn:
    conn.close()

執(zhí)行結(jié)果如下:

Error happens, rollback is call

因?yàn)榍皟蓷l數(shù)據(jù)是正確的插入操作,但是因?yàn)檎w回滾,所以數(shù)據(jù)庫里也沒有wangzhengyi4和bululu5這兩個(gè)數(shù)據(jù)的存在。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to handle API authentication in Python How to handle API authentication in Python Jul 13, 2025 am 02:22 AM

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

How to parse large JSON files in Python? How to parse large JSON files in Python? Jul 13, 2025 am 01:46 AM

How to efficiently handle large JSON files in Python? 1. Use the ijson library to stream and avoid memory overflow through item-by-item parsing; 2. If it is in JSONLines format, you can read it line by line and process it with json.loads(); 3. Or split the large file into small pieces and then process it separately. These methods effectively solve the memory limitation problem and are suitable for different scenarios.

Python for loop over a tuple Python for loop over a tuple Jul 13, 2025 am 02:55 AM

In Python, the method of traversing tuples with for loops includes directly iterating over elements, getting indexes and elements at the same time, and processing nested tuples. 1. Use the for loop directly to access each element in sequence without managing the index; 2. Use enumerate() to get the index and value at the same time. The default index is 0, and the start parameter can also be specified; 3. Nested tuples can be unpacked in the loop, but it is necessary to ensure that the subtuple structure is consistent, otherwise an unpacking error will be raised; in addition, the tuple is immutable and the content cannot be modified in the loop. Unwanted values can be ignored by \_. It is recommended to check whether the tuple is empty before traversing to avoid errors.

how to check which storage engine is used in mysql how to check which storage engine is used in mysql Jul 13, 2025 am 02:00 AM

The method of viewing the storage engine of MySQL is as follows: 1. You can use the command SHOWVARIABLESLIKE'default_storage_engine'; 2. You can use the storage engine used to view a certain table to view the storage engine through SHOWCREATETABLE or query information_schema.TABLES; 3. You can use SELECTTABLE_NAME,ENGINEFROMinformation_schema.TABLESWHERETABLE_SCHEMA='your_database'; 4. Other methods include on the command line

mysql temporary table vs memory table mysql temporary table vs memory table Jul 13, 2025 am 02:23 AM

Temporary tables are tables with limited scope, and memory tables are tables with different storage methods. Temporary tables are visible in the current session and are automatically deleted after the connection is disconnected. Various storage engines can be used, which are suitable for saving intermediate results and avoiding repeated calculations; 1. Temporary tables support indexing, and multiple sessions can create tables with the same name without affecting each other; 2. The memory table uses the MEMORY engine, and the data is stored in memory, and the restart is lost, which is suitable for cache small data sets with high frequency access; 3. The memory table supports hash indexing, and does not support BLOB and TEXT types, so you need to pay attention to memory usage; 4. The life cycle of the temporary table is limited to the current session, and the memory table is shared by all connections. When choosing, it should be decided based on whether the data is private, whether high-speed access is required and whether it can tolerate loss.

How to prevent a method from being overridden in Python? How to prevent a method from being overridden in Python? Jul 13, 2025 am 02:56 AM

In Python, although there is no built-in final keyword, it can simulate unsurpassable methods through name rewriting, runtime exceptions, decorators, etc. 1. Use double underscore prefix to trigger name rewriting, making it difficult for subclasses to overwrite methods; 2. judge the caller type in the method and throw an exception to prevent subclass redefinition; 3. Use a custom decorator to mark the method as final, and check it in combination with metaclass or class decorator; 4. The behavior can be encapsulated as property attributes to reduce the possibility of being modified. These methods provide varying degrees of protection, but none of them completely restrict the coverage behavior.

Securing MySQL installations with SSL/TLS connections Securing MySQL installations with SSL/TLS connections Jul 13, 2025 am 02:16 AM

To configure MySQL's SSL/TLS encrypted connection, first generate a self-signed certificate and correctly configure the server and client settings. 1. Use OpenSSL to generate CA private key, CA certificate, server private key and certificate request, and sign the server certificate yourself; 2. Place the generated certificate file in the specified directory, and configure the ssl-ca, ssl-cert and ssl-key parameters in my.cnf or mysqld.cnf and restart MySQL; 3. Force SSL on the client, restrict users from connecting only through SSL through the GRANTUSAGE command, or specify the --ssl-mode=REQUIRED parameter when connecting; 4. After logging in, execute \s to check SSL status confirmation

what is if else in python what is if else in python Jul 13, 2025 am 02:48 AM

ifelse is the infrastructure used in Python for conditional judgment, and different code blocks are executed through the authenticity of the condition. It supports the use of elif to add branches when multi-condition judgment, and indentation is the syntax key; if num=15, the program outputs "this number is greater than 10"; if the assignment logic is required, ternary operators such as status="adult"ifage>=18else"minor" can be used. 1. Ifelse selects the execution path according to the true or false conditions; 2. Elif can add multiple condition branches; 3. Indentation determines the code's ownership, errors will lead to exceptions; 4. The ternary operator is suitable for simple assignment scenarios.

See all articles