Python learning notes – MySQL database connection related

Time:2021-8-18
Import pymssql # import pymssql module

server = "localhost"
user = "root"
password = "root"
charset = "cp936"
database = "text_01"

def conn():
    Connect = pymssql.connect (server, user, password, database, charset) # server name, account, password, database name
    if connect:
        Print ("connection succeeded!")
        cursor = con.cursor()
        #Query database content
    	sqlfirst = "select * from datatable"
    	cursor.execute(sqlfirst)
        #Get query results. If there are multiple query results, use: cursor. Fetchall()
    	result = cursor.fetchone()

if __name__ == '__main__':
    conn = conn()

The above is the basic code example of Python connecting to MySQL database. It should be noted that if there is Chinese in your database, you must set the coding format as “cp936”