Using the configuration file to save fixed connection data, it is more convenient to change.
1. Create a new configuration file: Sqlconfig.config, take the database as an example.
The content is as follows, and of course you can add multiple
[Database1]
database=db_test
host=test.sqlserver.rds.alincs.com,3433
user=qhlt_just
pwd=zHi4M63wIddlSDK2nY
[Database2]
database=db_test
host=test.sqlserver.rds.alincs.com,3433
user=qhlt_just
pwd=zHi4M63wIddlSDK2nY
。。。。。
2. Read the configuration file. The class that the user configparser to read the file.
The code is as follows
# coding = utf-8
import ConfigParser
def getSQLCONFIG (filename):
cf = ConfigParser.ConfigParser ()
cf.read (filename) #Read configuration file
# Read corresponding file parameters
_database = cf.get ("Database1", "database")
_host = cf.get ("Database1", "host")
_user = cf.get ("Database1", "user")
_pwd = cf.get ("Database1", "pwd")
print "% s,% s,% s,% s"% (_database, _host, _user, _pwd)
return _database, _host, _user, _pwd #return required parameters
3. Connect to the database and install the PYODBC library. Connecting to a SQL Server database
# coding = utf-8
import pyodbc
import ReadConfig
#Call to read the configuration file
c = ReadConfig.getSQLCONFIG (r‘C: \ Users \ Administrator \ PycharmProjects \ untitled1 \ com \ SQLqueray \ SQlconfig.config ‘)
conn_info = 'DRIVER = {SQL Server}; DATABASE =% s; SERVER =% s; UID =% s; PWD =% s'% (c [0], c [1], c [2], c [3 ])
mssql_conn = pyodbc.connect (conn_info)
mssql_cur = mssql_conn.cursor ()
#Query Name and User ID
result = mssql_cur.execute ("select Fullname, id from god where id = 19688")
#Circular print query results
for row in result:
print row [0], row [1]
Python reads the configuration file and connects to the database SQL Server