import pymysql
#主機名 使用者 密碼 庫
db = pymysql.connect("localhost", "root", "fs.com", "test")
#建立物件
cursor = db.cursor()
#給出執行sql語句
sql = "select version()"
#執行cursor.execute(sql)
#過去返回資訊
data = cursor.fetchall()
print(data)
#斷開cursor.close()
db.close()
建立資料庫表:import pymysql
db = pymysql.connect("localhost", "root", "fs.com", "test")
cursor = db.cursor()
cursor.execute(drop table if exists bandcard)
建立表sql = 'create tabele bandcard (
id int auto_increment primary key,
money int not null
)''cursor.close()
db.close()
插入資料:如果插入資料錯誤,回滾之前狀態
try :
cursor.execute(sql)
db.commit()
except:
db.rollback
查詢操作:
fetchone()
獲取下乙個查詢結果集,結果集是乙個物件
fetchall()接受全部的返回的行
rowcount()是乙個唯讀屬性,返回 execute() 方法影響的行數
import pymysql
db = pymysql.connect("localhost", "root", "fs.com", "test")
cursor = db.cursor()
sql = 'select * from bandcard where money > 400'
try :
cursor.execute(sql)
reslist = cursor.fetchall()
for row in reslist:
print ("%d-%d" % (row[0], row[1]))
except:
db.rollback
import pymysql
class usersql():
def __init__(self, host, user, passwd, dbname):
self.host = host
self.user = user
self.passwd = passwd
self.db = dbname
def connet(self):
self.db = pymysql.connect(self.host, self.user, self.passwd, self.dbname)
self.cursor = self.db.cursor()
def close(self):
self.cursor.close()
self.db.close()
def get_one(self, sql):
res = none
try :
self.connet()
self.cursor.execute(sql)
res = self.cursor.fetchone()
except:
print("查詢失敗")
return res
def get_all(self, sql):
res = ()
try :
self.connet()
self.cursor.execute(sql)
res = self.cursor.fetchall()
except:
print("查詢失敗")
return res
def insert(self, sql):
return self.__edit(sql)
def delete(self, sql):
return self.__edit(sql)
def update(self, sql):
return self.__edit(sql)
def __edit(self, sql):
count = 0
try :
self.count()
count = self.cursor.execute(sql)
self.db.rollback
self.close()
except:
print("事務提交失敗")
self.db.rollback
使用from usersql import usersql
s = usersql("localhost", "root", "fs.com", "test")
res = s.get_all("select * from test")
for row in res:
print ("%d-%d" % (row[0], row[1]))
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連線資料庫
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...
python連線資料庫
1 安裝mysql ubantu下安裝不撰述 2 安裝python版本的mysql開發包 sudo apt get install python mysqldb3 編寫python usr bin python coding utf 8 import mysqldb 引入mysqldb包 開啟資料庫...