Python reads INI file, operates MySQL, sends mail instance _python

Source: Internet
Author: User
Tags postgresql psql read ini file

I am free to do nothing, 2014 too pompous, blog also did not write a few, ah ~ ~ ~ With this to record the upcoming 2014

Python operates on a variety of databases all over the street, but I still like my style, it involves other operations, but the focus is on the operation of the database. Ah ~ ~

Python operations MySQL

First of all, I am accustomed to write configuration information to the configuration file, so that it can be modified without the source code, and then write a common function for the call

Create a new configuration file, named Conf.ini, you can write various configuration information, but all indicate the node (file format requirements or more stringent):

Copy Code code as follows:

[App_info]
Database=test
User=app
password=123456
host=172.17.1.1
port=3306

[Mail]
Host=smtp.163.com
Mail_from=zhoujie0111@126.com
password=654321
Send_to=zhoujie0111@139.com;zhoujie0111@163.com

In the same directory under the new file db.py, the vigorous code is as follows, do not explain:

Copy Code code as follows:

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

Import MySQLdb #首先必须装这两个包
Import Configparser

Cf=configparser.configparser ()
Cf.read ("Conf.ini")

Database=cf.get ("App_info", "DATABASE")
User=cf.get ("App_info", "USER")
Password=cf.get ("App_info", "PASSWORD")
Host=cf.get ("App_info", "HOST")
Port=cf.get ("App_info", "PORT")

def mysql (SQL):
Try
Conn=mysqldb.connect (Host=host,user=user,passwd=password,db=database,port=port)
cur = conn.cursor ()
Cur.execute (SQL)
rows = Cur.fetchall ()
Conn.commit () #这个对于增删改是必须的, otherwise the transaction did not commit unsuccessfully
Cur.close ()
Conn.close ()
return rows
Except Mysqldb.error,e:
Print "Mysql Error%d:%s"% (E.args[0], e.args[1])

The above is a way to encapsulate the operation of the database, just provide an SQL statement, CRUD can be manipulated. Some of the following YY data to test the specific use of additions and deletions (easy, I really busy), and then the above code to write:

Copy code code as follows:

def operation ():
#查询
select = MySQL (' select * from Test ')

#插入
'''
To insert this place there are 2 points to note:
1. Insert a few columns as specified below, insert all can not specify a column, but must be inserted after the value in order
2. Note that the following type column has a backslash on either side, because type has a table in my database called this, or you can call it a keyword, without a backslash insertion fails.
3. This is not to say, hehe, the digit placeholder is%d, the string is in%s, and the string placeholder must be enclosed in double quotes
'''
insert = MySQL (' INSERT into Test (name,number, ' type ') VALUES ('%s ',%d, '%s ') '% (' Jzhou ', MB, ' VIP '))

#更新
MySQL (' Update test set number=%d where name= '%s '% ($, ' Jzhou '))

#删除
Delete = MySQL (' Delete from test where number =%d and ' type ' = '%s '% (' Jzhou ')]

Return select #我返回这个是为了下面发送邮件用的 and add the ability to send mail

I just want to make this simple operation more complex, add a message to send the function, but also the above code:

Copy Code code as follows:

Mailto_list=[]
Send_info=cf.get ("Mail", "send_to")
Send_array=send_info.split (";")
For I in range (len (send_array)):
Mailto_list.append (Send_array[i])

Mail_host=cf.get ("Mail", "host")
Mail_from=cf.get ("Mail", "Mail_from")
Mail_password=cf.get ("Mail", "password")

def send_mail (to_list,sub,content):
Me=mail_from
Msg=mimetext (content,_subtype= ' HTML ', _charset= ' utf-8 ')
msg[' Subject ']=sub
msg[' from ']=me
msg[' to ']= '; Join (To_list)
Try
S=smtplib. SMTP ()
S.connect (Mail_host)
S.login (Mail_from,mail_password)
S.sendmail (me,to_list,msg.as_string ())
S.close ()
Return True
Except Exception,e:
Print str (e)
Return False

Send mail configuration I also write in the Conf.ini, call in the main function to send a message to end this thing:

Copy Code code as follows:

if __name__ = = ' __main__ ':
Sub = U ' Don't ask me why I write this blog, leisure, is willful! '
Content = operation ()
If Send_mail (mailto_list,sub,content):
print ' Send Success '
Else
print ' Send failed '

In fact, I would also like to say that Python operation PostgreSQL, similar to MySQL, download package psycopg2, not the same is the PostgreSQL executed in the SQL statements should be double quotes, to feel:

Copy Code code as follows:

#-*-coding:utf-8-*-
Import PSYCOPG2
Import Configparser

Cf=configparser.configparser ()
Cf.read ("Conf.ini")

Database=cf.get ("Cmdb_info", "DATABASE")
User=cf.get ("Cmdb_info", "USER")
Password=cf.get ("Cmdb_info", "PASSWORD")
Host=cf.get ("Cmdb_info", "HOST")
Port=cf.get ("Cmdb_info", "PORT")

def psql (SQL):
Try
conn = Psycopg2.connect (Database=database, User=user, Password=password, Host=host, Port=port)
cur = conn.cursor ()
Cur.execute (SQL)
rows = Cur.fetchall ()
Conn.commit ()
Cur.close ()
Conn.close ()
return rows
Except Exception,e:
Print E

Def psql_oper ():
sql= "SELECT \" name\ ", \" type\ "from \" test\ "where \" name\ "= ' Jzhou '"
Rows=psql (SQL)
Print rows

I concluded that this blog is simple, but contains three important points of knowledge, ^_^

1, Python read INI file (to import Configparser)
2, python operation MySQL
3, Python send mail

4, published by the practice of testing, even if very simple, this is an attitude!

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.