Mysqldb of Python module: connect to MySQL database with Python

Source: Internet
Author: User

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 ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.