Several main methods of python connecting to Database
This article mainly introduces several main methods of python to connect to the database, hoping to supplement and update some knowledge for you. If you have other questions to understand, you can continue to follow my updated article in the industry information.
There are several methods for python to connect to the database, but the format of the data retrieved from the database is somewhat different, and it is more troublesome to retrieve the data in tuple format. Then it introduces a connection method to retrieve the data in list format, which is more convenient for data processing and use in list format.
#! / usr/bin/python
#-*-coding: utf-8-*-
#! / usr/bin/env python
Import MySQLdb
From commands import getstatusoutput, getoutput
Import sys
Reload (sys)
Sys.setdefaultencoding ('utf-8')
Cmd =''mysql-h host address connection-u user name-p password-e "use database name; SELECT XXX"''
(result,info) = getstatusoutput (cmd) # info is the data value, result is the execution
Info = info.splitlines ()
File = open ("name.txt",'w') # Open the txt file
File.write ("xxx,xxx,xxx") # writes the first row of data to txt
# write the checked data to the txt file line by line
File.write ("\ n") # Line feeds
For i in range (len (info)):
If I! = 0 and I! = 1 # because the password is written in the file, a line of password alarm will be reported.
File.write (info [I]) # and the data retrieved in the first row is the name of the data header field, so it is useless
File.write ("\ n") # leaves only valid data to write to the file
File.close () # close tx
Read the above about the main methods of python database connection, hope to bring some help to everyone in practical application. Due to the limited space in this article, it is inevitable that there will be deficiencies and need to be supplemented. If you need more professional answers, you can contact us on the official website for 24-hour pre-sales and after-sales to help you answer questions at any time.