#encoding=utf-8
import pymysql
import student
class jdbc_connect:
'數據庫執行操作'
#執行對象
cursor="";
db=False;
#連接數據庫
def __init__(self,host,username,password,database):
try:
jdbc_connect.db = pymysql.connect(host, username,password, database, charset="utf8");
jdbc_connect.cursor = self.db.cursor();
except BaseException:
print("連接數據庫異常")
self.db.close()
'查詢數據庫 並且返還對象'
def select(self,sql):
jdbc_connect.cursor.execute(sql);
students=self.cursor.fetchall();
return students;
'向數據庫添加數據'
'0成功/1失敗'
def insert(self,sql):
try:
jdbc_connect.cursor.execute(sql);
jdbc_connect.db.commit();
except pymysql.DataError:
jdbc_connect.db.rollback();
print("執行添加操作失敗")
return "1"
else:
return "0"
'修改'
def update(self,sql):
try:
jdbc_connect.cursor.execute(sql);
jdbc_connect.db.commit();
except pymysql.DataError:
jdbc_connect.db.rollback();
print("執行修改操作失敗")
return "1"
else:
return "0"
'刪除'
def delete(self,sql):
try:
jdbc_connect.cursor.execute(sql);
jdbc_connect.db.commit();
except pymysql.DataError:
jdbc_connect.db.rollback();
print("執行刪除操作失敗")
return "1"
else:
return "0"
'關閉數據庫連接'
def closedb(self):
try:
self.cursor.close();
self.db.close();
except BaseException:
print("db close error")
-------調用---------
import student
import jdbc_connect
dbt=jdbc_connect.jdbc_connect("localhost", "root", "ok", "pythontest")
str1="select * from student"
#學生集合
students=dbt.select(str1)
print(students)
# insert_str="insert into student values('王五1',18,'sa51df321s')"
# print(dbt.insert(insert_str)
# print(students))
# students=dbt.select(str1)
# update_str="update student set name='王二麻子' where name='王五'"
# print(dbt.update(update_str))
delete_str="delete from student where name='王二麻子'"
dbt.delete(delete_str)
print(dbt.select(str1))