python連線MySQL基本操作

2021-10-07 11:14:32 字數 1455 閱讀 2470

import pymysql

建立連線

db = pymysql.connect(『localhost』,『root』,『123456』,『test』)

sql = 『select * from score where id=10』

建立游標物件

cur = db.cursor()

指定執行sql

a = cur.execute(sql)

這個是對建立的游標物件來使用的

fetchall 取表中所有行資料,放在乙個元組裡,每一行資料又是乙個元組

fetchone 按順序取資料。從第一行開始,每次取一行

fetchmany指定範圍取行資料

print(cur.fetchone())

關閉連線

db.close()

mysql刪除表

import pymysql

建立連線:ip、使用者名稱、密碼、資料庫(注意預設3306可以不寫,但是如果指定了埠,就需要)

db = pymysql.connect(『localhost』,『root』,『123456』,『test』)

建立游標物件

cur = db.cursor()

刪除表

sql = 『』』 drop table tecah』』』

執行sql

cur.execute(sql)

提交事務,相當儲存修改

db.commit()

關閉連線

db.close()

mysql修改資料

import pymysql

db = pymysql.connect(『localhost』,『root』,『123456』,『test』)

建立游標物件

cur = db.cursor()

新增資料

sql = 『insert into score values (11,903,「日語課」,90)』

修改資料

sql = 『update score set grade=100 where id=11』

sql = 『delete from score where id=11』

執行sql

cur.execute(sql)

提交事務

db.commit()

關閉連線

db.close()

Python高階 連線 Mysql

本篇文章主要用 pymysql 來實現python3 mysql資料的連線。git clone cd pymysql python3 setup.py install 安裝過程如下圖所示 開啟資料庫連線 db pymysql.connect localhost username password t...

python連線MySQL示例

python連線mysql示例一 開啟資料庫連線 connect,connect,connection import pymysql db pymysql.connect host localhost port 3306 user root passwd 123456 db stu charset ...

JDBC連線MySQL的基本使用

b.statement物件的executequery 方法 string jdbc driver com.mysql.cj.jdbc.driver class.forname jdbc driver useunicode ture charactorencoding utf 8 設定utf8字符集 ...