MySQL is an excellent open-source database and is widely used. Therefore, it is necessary to briefly introduce how to operate MySQL databases using python. Python operating database needs to install a third-party module in the http://mysql-python.sourceforge.net/
Download and documentation are available.
Because the python database module has specific specifications for the database module, no matter which database method is used, it is similar. Here we will provide a demonstration.Code:
#
-*-Encoding: gb2312 -*-
Import
OS, sys, string
Import
Mysqldb
#
Connect to database
Try
:
Conn
=
Mysqldb. Connect (host
=
'
Localhost
'
, User
=
'
Root
'
, Passwd
=
'
Xxxx
'
, DB
=
'
Test1
'
)
Except
Exception, E:
Print
E
SYS. Exit ()
#
Get cursor object for operation
Cursor
=
Conn. cursor ()
#
Create a table
SQL
=
"
Create Table if not exists test1 (name varchar (128) primary key, age int (4 ))
"
Cursor.exe cute (SQL)
#
Insert data
SQL
=
"
Insert into test1 (name, age) values ('% s', % d)
"
%
(
"
Zhaowei
"
,
23
)
Try
:
Cursor.exe cute (SQL)
Except
Exception, E:
Print
E
SQL
=
"
Insert into test1 (name, age) values ('% s', % d)
"
%
(
"
Zhang San
"
,
21
)
Try
:
Cursor.exe cute (SQL)
Except
Exception, E:
Print
E
#
Insert multiple
SQL
=
"
Insert into test1 (name, age) values (% s, % s)
"
Val
=
((
"
Li Si
"
,
24
),(
"
Wang Wu
"
,
25
),(
"
Hong Liu
"
,
26
))
Try
:
Cursor.exe cute.pdf (SQL, Val)
Except
Exception, E:
Print
E
#
Query data
SQL
=
"
Select * From test1
"
Cursor.exe cute (SQL)
Alldata
=
Cursor. fetchall ()
#
If any data is returned, it will be output cyclically. alldata has a two-dimensional list.
If
Alldata:
For
REC
In
Alldata:
Print
REC [0], REC [
1
]
Cursor. Close ()
Conn. Close ()