1.首先在python中安裝驅動模塊:pip install?pymysql
2.連接到數(shù)據(jù)庫:
使用pymysql.connect(主機名host糠聪,端口port,登錄用戶user袋狞,登錄密碼password崖蜜,數(shù)據(jù)庫database)
mySqlCon = pymysql.connect(host ='localhost', port =3306 , user ='root',password ='123123',database ='edu_app')
3.創(chuàng)建一個游標:
cur = mySqlCon.cursor()
4.執(zhí)行對應的sql語句:
selectSql = 'select * from course where name = \'test\''
res = cur.execute(selectSql)
5.打印sql執(zhí)行結果:
print(res)
6.獲取一條記錄:
data_one = cur.fetchone()
print(data_one)
7.獲取多條記錄:
data_all = cur.fetchall()
print(data_all)
實際代碼如下:
import pymysql.cursors
#1.連接到數(shù)據(jù)庫
mySqlCon = pymysql.connect(host ='ip', port =3306 , user =user,password ='123123',database ='edu_app')
#2.創(chuàng)建一個游標
cur = mySqlCon.cursor()
#3.執(zhí)行對應的sql(sele)excute
selectSql ='select * from course where name = \'test\''
res = cur.execute(selectSql)
#4.打印查詢結果(一共有幾條數(shù)據(jù))
print(res)
#5.獲取一條數(shù)據(jù)
data_one = cur.fetchone()
print(data_one)
#6.獲取多條數(shù)據(jù)
data_all = cur.fetchall()
print(data_all)
返回結果如下: