Install and use MySQLdb and MySQLdb
I. Installation
Install the compiled version (this method is simple and convenient ):
Http://www.codegood.com/downloads
Download the package from your system and double-click it to install it.
Import MySQLdb to check whether the operation is successful.
My, win7, 32-bit, and 2.7
MySQL-python-1.2.3.win-amd32-py2.7.exe
Ii. Use
#! /Usr/bin/python
# Encoding: UTF-8
Import time, MySQLdb
# Open a database connection
Db = MySQLdb. connect ("localhost", "root", "root", "Python ")
# Use the cursor () method to obtain the operation cursor
Cursor = db. cursor ()
# Deleting a table
SQL = "drop table if exists thinkgamer"
Cursor.exe cute (SQL)
# Create
SQL = "create table if not exists thinkgamer (name varchar (128) primary key, created int (10 ))"
Cursor.exe cute (SQL)
# Write
SQL = "insert into thinkgamer (name, created) values (% s, % s )"
Param = ("aaa", int (time. time ()))
N = cursor.exe cute (SQL, param)
Print 'insert', n
# Write multiple rows
SQL = "insert into thinkgamer (name, created) values (% s, % s )"
Param = ("bbb", int (time. time (), ("ccc", 33), ("ddd", 44 ))
N = cursor.exe cute.pdf (SQL, param)
Print "insertworkflow", n
# Update
SQL = "update thinkgamer set name = % s where name = 'aaa '"
Param = ("zzz ")
N = cursor.exe cute (SQL, param)
Print "updata", n
# Query
N = cursor.exe cute ("select * from thinkgamer ")
For row in cursor. fetchall ():
Print row
For r in row:
Print r
# Delete
SQL = "delete from thinkgamer where name = % s"
Param = ("bbb ")
N = cursor.exe cute (SQL, param)
Print "delete", n
# Query
N = cursor.exe cute ("select * from thinkgamer ")
Print cursor. fetchall ()
Cursor. close ()
# Submit
Db. commit ()
# Disable
Db. close ()
Output result:
Insert 1
Insert00003
Updata 1
('Zzz', 1436067892L)
Zzz
1436067892
('Bbb ', 1436067892L)
Bbb
1436067892
('Ccc ', 33L)
Ccc
33
('Ddd ', 44L)
Ddd
44
Delete 1
('Zzz', 1436067892L), ('ccc ', 33L), ('ddd', 44L ))
For more details, see MySQLdb User's Guide.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.