python操作mysql資料庫,pymysql

2021-08-29 12:17:51 字數 1412 閱讀 7798

參考

pip3 install pymysql

如果是在pycharm裡安裝pymysql模組,如圖進去安裝介面,搜尋pymysql然後安裝就行。

很簡單,連線——傳送sql語句執行——關閉

import pymysql

# 建立連線

port:mysql預設埠3306;

user:資料庫使用者名稱一般root;

passwd:安裝資料庫你設定的密碼

db:要操作的資料庫的名稱(第一次要在mysql的命令列裡先建立自己的資料庫)

charset:編碼格式'''

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='35278479', db= 'us_states', charset='utf8')

# 建立游標,相當於mysql命令列的那個游標,可以輸入sql語句的地方

cursor = conn.cursor()

# 執行sql,並返**影響行數

#建立states**,有id,state,population這3個列

effect_row = cursor.execute("create table states (id int not null primary key auto_increment, state char(25), population int(9))")

print(effect_row)

#插入資料

effect_row = cursor.execute("insert into states (id, state, population) values (1, '加州', 5)")

print(effect_row)

effect_row = cursor.execute("select * from states")

print(effect_row)

#接受一行

row_1 = cursor.fetchone()

print(row_1)

#接受n行

row_1 = cursor.fetchone(5)

print(row_1)

#接受全部行

row_all = cursor.fetchall()

print(row_all)

# 提交,不然無法儲存新建或者修改的資料

conn.commit()

# 關閉游標

cursor.close()

# 關閉連線

conn.close()

python操作mysql查詢資料

首先需要連線資料庫,然後才查詢出資料。例如下表名字為 sinauser iduse id use name11 db12 2db233 db3class database def init self self.conn mysqldb.connect 連線資料庫 host 連線你要取出資料庫的ip,...

python操作MySQL資料庫

堅持每天學一點,每天積累一點點,作為自己每天的業餘收穫,這個文章是我在吃飯的期間寫的,利用自己零散的時間學了一下python操作mysql,所以整理一下。我採用的是mysqldb操作的mysql資料庫。先來乙個簡單的例子吧 import mysqldb try conn mysqldb.connec...

Python操作Mysql資料庫

coding utf8 author yangjing import mysqldb 查詢。def select host user root password port 3306,db sql connect mysqldb.connect host host,user user,passwd p...