Python連線資料庫

2021-08-08 14:56:45 字數 2385 閱讀 1653

#!/usr/bin/env python

# coding:utf-8

import sys

# reload(sys)

# sys.setdefaultencoding("utf-8")

import pymysql

import pymysql.cursors

#!/usr/bin/env python

# coding:utf-8

import sys

# reload(sys)

# sys.setdefaultencoding("utf-8")

import pymysql

import pymysql.cursors

db = pymysql.connect(host='127.0.0.1', user='root', passwd='', db='douban', port=3306, charset='utf8')

db.commit(true)

cursor = db.cursor()

# create

# 讀取資料

fr = open('../data/douban_movie_clean.txt', 'r',encoding="utf-8")

print("----")

count = 0

for line in fr:

try:

count += 1

# count表示當前處理到第幾行了

print (count)

# 跳過表頭

if count == 1:

continue

# strip()函式可以去掉字串兩端的空白符

# split()函式按照給定的分割符將字串分割為列表

line = line.strip().split('^')

# 插入資料,注意對齊字段

# execute()函式第乙個引數為要執行的sql命令

# 這裡用字串格式化的方法生成乙個模板

# %s表示乙個佔位符

# 第二個引數為需要格式化的引數,傳入到模板中

cursor.execute("insert into movie(title, url, rate, length, description) values(%s, %s, %s, %s, %s)", [line[1], line[2], line[4], line[-3], line[-1]])

except exception as e:

print("error")

# 關閉讀檔案

fr.close()

# update

# 更新需要提供條件、需要更新的字段、更新的新值

# 以下對於id為1的記錄,將其title和length兩個字段進行更新

cursor.execute("update movie set title=%s, length=%s where id=%s", ['全棧資料工程師養成攻略', 999, 1])

# read

# 讀取全部資料的全部字段

cursor.execute("select * from movie")

movies = cursor.fetchall()

# 返回元組,每一項都是乙個字典

# 對應一條記錄的全部欄位和字段值

print (type(movies), len(movies), movies[0])

# 讀取一條資料的部分字段

# 返回乙個字段,對應所選擇的部分欄位和字段值

cursor.execute("select id, title, url from movie where id=2")

movie = cursor.fetchone()

print (type(movie), len(movie), movie)

# # 讀取一條資料的部分字段

# # 按id降序排序,預設為公升序

cursor.execute("select id, title, url from movie order by id desc")

movie = cursor.fetchone()

print (type(movie), len(movie), movie)

# # delete

# # 刪除資料務必要提供刪除條件

# # 此處刪除id為1的記錄

cursor.execute("delete from movie where id=%s", [1])

# 關閉資料庫連線

cursor.close()

db.close()

大概流程,涉及到具體資料庫更細粒度的操作,要再學習。

python 連線資料庫

原文 原文1 安裝mysql python pip install mysql python dome1 def db mange db bank conn none try 開啟資料庫連線 conn mysqldb.connect localhost root 123456 db bank 獲取操...

python連線資料庫

1 安裝mysql ubantu下安裝不撰述 2 安裝python版本的mysql開發包 sudo apt get install python mysqldb3 編寫python usr bin python coding utf 8 import mysqldb 引入mysqldb包 開啟資料庫...

python連線資料庫

連線的是mysql資料庫 首先,在idea中執行命令 pip install pymysql 安裝可執行的檔案 檔案安裝完成後,一般會在專案的venv lib site packages 下,需要將pymysql資料夾放到lib下面 此時.py中的import pymysql不報錯 我們就可以使用運...