標籤:遊標對象 one date select coding imp 結果 ack python
Python3安裝模組
pip3 install pymysql
1、Python3查詢資料
import sysimport pymysql# 開啟資料庫連接db = pymysql.connect("10.0.0.101","sheng","123456","Sheng_DB" ,charset=‘utf8‘)# 使用cursor()方法擷取操作遊標cursor = db.cursor()# SQL 查詢語句sql = "SELECT * FROM student"try: # 執行SQL語句 cursor.execute(sql) # 擷取所有記錄列表 results = cursor.fetchall() print(results) print(len(results[0])) for row in results: sid = row[0] gender = row[1] class_id=row[2] sname=row[3] # 列印結果 print("id是:%s,性別:%s,班級編號:%s,姓名:%s" %(sid, gender,class_id,sname )) # print(results)except: print("Error: unable to fetch data")# 關閉資料庫連接db.close()
2、Python插入資料代碼
# -*- coding: utf-8 -*-__author__ = ‘ShengLeQi‘import pymysql# # 開啟資料庫連接class MySql(object): def __init__(self,ip,user_name,passwd,db, char=‘utf8‘): self.ip = ip # self.port = port self.username=user_name self.passwd=passwd self.mysqldb=db self.char=char self.MySQL_db = pymysql.connect( host=self.ip, user=self.username, passwd=self.passwd, db=self.mysqldb, charset=self.char) def Sql_exe(self,sql): cursor = self.MySQL_db.cursor() MySQL_sql = sql try: # 執行SQL語句 cursor.execute(MySQL_sql) self.MySQL_db.commit() except: print("Error: unable to fetch data") self.MySQL_db.close() self.MySQL_db.close() # MySql_t=MySql("10.0.0.101","sheng","123456","Sheng_DB",char=‘utf8‘ )MySql_t=MySql("10.0.0.101","novel","123456","Novel",char=‘utf8‘ ) #Novel#sql="insert into Novel(name,conext) values(‘name_t‘,‘connent_t‘)"MySql_t.Sql_exe(sql)
3、修改資料庫:
import pymysql # 開啟資料庫連接(ip/資料庫使用者名稱/登入密碼/資料庫名) db = pymysql.connect("localhost", "root", "root", "test") # 使用 cursor() 方法建立一個遊標對象 cursor cursor = db.cursor() # SQL 更新語句 sql = "UPDATE user SET name = ‘Bob‘ WHERE id = 1" try: # 執行SQL語句 cursor.execute(sql) # 提交到資料庫執行 db.commit() except: # 發生錯誤時復原 db.rollback() # 關閉資料庫連接 db.close()
4、修改資料庫
import pymysql # 開啟資料庫連接(ip/資料庫使用者名稱/登入密碼/資料庫名) db = pymysql.connect("localhost", "root", "root", "test") # 使用 cursor() 方法建立一個遊標對象 cursor cursor = db.cursor() # SQL 刪除語句 sql = "DELETE FROM user WHERE id = 1" try: # 執行SQL語句 cursor.execute(sql) # 提交修改 db.commit() except: # 發生錯誤時復原 db.rollback() # 關閉資料庫連接 db.close()
Python3串連Mysql