Example of connecting python to mysql database (add, delete, and modify operations)

Source: Internet
Author: User

I. Related code
Database Configuration class MysqlDBConn. py

Copy codeThe Code is as follows:
# Encoding = UTF-8
'''
Created on 2012-11-12

Mysql Conn connection class
'''

Import MySQLdb

Class DBConn:

Conn = None

# Establish a connection to the Database System
Def connect (self ):
Self. conn = MySQLdb. connect (host = "localhost", port = 3306, user = "house", passwd = "house", db = "house", charset = "utf8 ")

# Retrieve operation cursor
Def cursor (self ):
Try:
Return self. conn. cursor ()
Failed T (AttributeError, MySQLdb. OperationalError ):
Self. connect ()
Return self. conn. cursor ()

Def commit (self ):
Return self. conn. commit ()

# Closing a connection
Def close (self ):
Return self. conn. close ()

MysqlDemo. py class

Copy codeThe Code is as follows:
# Encoding = UTF-8
'''
Created on 2012-11-12

@ Author: Steven

Mysql operation Demo
Done: Creates tables, deletes tables, adds, deletes, and modifies data, and inserts data in batches.
'''
Import MysqlDBConn

Dbconn = MysqlDBConn. DBConn ()

Def process ():
# Establish a connection
Dbconn. connect ()
# Deleting a table
DropTable ()
# Creating a table
CreateTable ()
# Batch insert data
InsertDatas ()
# Single insert
InsertData ()
# Update data
UpdateData ()
# Deleting data
DeleteData ()
# Querying data
QueryData ()
# Releasing a connection
Dbconn. close ()

Def insertDatas ():
SQL = "insert into lifeba_users (name, realname, age) values (% s, % s, % s )"
Tmp = ('steven 1', 'test 1', 26), ('steven 2', 'test 2', 25 ))
Executetasks (SQL, tmp)

Def updateData ():
SQL = "update lifeba_users set realname = '% s' where name = 'steven 1'" % ("Test 1 modify ")
Execute (SQL)

Def deleteData ():
SQL = "delete from lifeba_users where id = 2"
Execute (SQL)

Def queryData ():
SQL = "select * from lifeba_users"
Rows = query (SQL)
PrintResult (rows)

Def insertData ():
SQL = "insert into lifeba_users (name, realname, age) values ('% s',' % s', % s)" % ("Steven 3", "Test 3 ", "26 ")
Print SQL
Execute (SQL)

Def execute.pdf (SQL, tmp ):
'''Insert multiple pieces of data '''
Conn = dbconn. cursor ()
Conn.exe cute.pdf (SQL, tmp)

Def execute (SQL ):
'''Execute SQL '''
Conn = dbconn. cursor ()
Conn.exe cute (SQL)

Def query (SQL ):
'''Query SQL '''
Conn = dbconn. cursor ()
Conn.exe cute (SQL)
Rows = conn. fetchmany (10)
Return rows

Def createTable ():
'''Create a table '''
Conn = dbconn. cursor ()
Conn.exe cute ('''
Create table 'lifeba _ users '(
'Id' int (11) not null auto_increment,
'Name' varchar (50) default NULL,
'Realname' varchar (50) default NULL,
'Age' int (11) default NULL,
Primary key ('id ')
) ENGINE = MyISAM default charset = utf8;
''')
# Dbconn. commit ()

Def dropTable ():
'''Delete table '''
Conn = dbconn. cursor ()
Conn.exe cute ('''
Drop table if exists 'lifeba _ users'
''')
# Dbconn. commit ()

Def printResult (rows ):
For row in rows:
For I in range (0, len (row): # traverse the Array
Print row [I], # Add, print without line breaks
Print''

If _ name _ = '_ main __':

Process ()

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.