Get the App
SLTechnology News&Howtos  ›  Database  › 

Operate mysql database with python (simple query operation)

Shulou Source: shulou.com Published: 2022-06-01 18:25:34 10月04日 Update

1. Mysql installation

Ten thousand words are omitted here.

2. Pip installs the MySQLdb module

Sudo pip install mysql-python

3. Simple code

#! / usr/bin/env python#-*-coding: utf-8-*-import MySQLdb# establish a connection conn = MySQLdb.connect (host='127.0.0.1',user='root',passwd='1qaz#EDC',db='test_db') cur = conn.cursor () # create a cursor # description: connect method generates a connection object Access the database through this object # manipulate the data res = cur.execute ('select * from UserInfo') # execute the sql statement data = cur.fetchall () # read the execution result # close the database connection cur.close () conn.close () print res # print out how many pieces of data print data # print the actual content of the data

4. Query the data of the specified ID number

#! / usr/bin/env python#-*-coding: utf-8-*-import MySQLdb# establish a connection conn = MySQLdb.connect (host='127.0.0.1',user='root',passwd='1qaz#EDC',db='test_db') cur = conn.cursor () # manipulate the data sql = "select * from user where id=%s" # define sql statement params = ('3') # Parameter ID is 3cur.execute (sql Params) # execute the sql statement data = cur.fetchall () # close the database connection cur.close () conn.close () print data

Tags: Data database statement object utf-8 query code content parameter actual method module cursor result generation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Xiaomi MariaDB NVidia Shulou Information