데이터베이스 스키마 및 Python 데이터베이스 함수 생성 👨🏼💻
SQLite
Database 🎉를 사용했습니다.Draw을 사용하여 스키마를 만들기 시작했습니다.
• 다음에 대한 테이블 생성:
1. 생성자
2. 기브_투
3. 서버 정보
4. 포인트
• 그래서 찾아본 결과 Discord가 모든 메시지에 대해 고유한 Message_id를 생성했음을 알게 되었습니다Blog Link.
• Message_Id를 기본 키로 만들고 다른 모든 테이블에 대한 외래 키로 만들었습니다!
에서 많은 개선과 컨설팅을 거친 후 이것이 스키마의 모습입니다!
코드와 생각의 과정💭
섬기는 사람
CREATE TABLE "Server_Info" (
"channel_name" VARCHAR(255),
"channel_id" BIGINT,
"server_name" VARCHAR(255)
);
포인트들
CREATE TABLE "Points" (
"user_tag" INTEGER,
"username" VARCHAR(255),
"message_id" BIGINT,
"total_points" INTEGER,
"Is_Helper" BOOLEAN,
FOREIGN KEY("message_id") REFERENCES "Created_By"("message_id")
);
기븐_투
CREATE TABLE "Given_To" (
"ID" INTEGER AUTO INCREMENT,
"message_id" BIGINT,
"username" VARCHAR(255),
"user_id" BIGINT,
"user_tag" INTEGER,
"Is_Helper" BOOLEAN,
FOREIGN KEY("message_id") REFERENCES "Created_By"("message_id")
);
생성자
CREATE TABLE "Created_By" (
"ID" INTEGER AUTO INCREMENT,
"message_id" BIGINT,
"user_tag" INTEGER,
"username" VARCHAR(255),
"user_id" BIGINT,
"message_desc" VARCHAR(255),
"points_given" INTEGER,
"channel_name" VARCHAR(255),
"timestamp" DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY("message_id")
);
스키마와 테이블을 생성한 후에는 이제 작업을 수행할 함수python
를 생성할 시간입니다😄!
• 먼저 프로그램을 데이터베이스에 연결할 Connect_Function()을 만들었습니다.
def get_connection():
mydb = sqlite3.connect('points.db')
cursor = mydb.cursor()
return mydb, cursor
• 다음 단계는 CRUD 작업을 위한 함수 생성이었습니다(비록 delete
명령은 현재 사용되지 않습니다🙊).
Submitted_by 메서드
def submitted_by(msg_id, usr_tag, username, user_id, msg_desc, points, channel_name):
mydb, cursor = get_connection()
query = """
INSERT INTO Created_By (message_id, user_tag, username, user_id, message_desc, points_given, channel_name) VALUES (?, ?, ?, ?, ?, ?, ?);
"""
values = (msg_id, int(usr_tag), str(username), user_id, str(msg_desc), points, str(channel_name))
cursor.execute(query, values)
mydb.commit()
cursor.close()
mydb.close()
print('Inserted Data Successfully to the Created_By Database!')
서버 방식
def server(channel_name, channel_id, server_name):
mydb, cursor = get_connection()
query = """
INSERT INTO Server_Info (channel_name, channel_id, server_name) VALUES (?, ?, ?);
"""
values = (channel_name, channel_id, server_name)
cursor.execute(query, values)
mydb.commit()
cursor.close()
mydb.close()
print('Inserted Data Successfully to the Server Database!')
Given_to 메서드
def Given_To(msg_id, username, user_id, user_tag, Is_helper):
mydb, cursor = get_connection()
query = """
INSERT INTO Given_To (message_id, username, user_id, user_tag, Is_Helper) VALUES (?, ?, ?, ?, ?);
"""
values = (msg_id, str(username), user_id, int(user_tag), Is_helper)
cursor.execute(query, values)
mydb.commit()
cursor.close()
mydb.close()
print('Inserted Data Successfully to the Given_to Database!')
After some try/error method, I found out that the user points should be updated when points are given to them multiple times.
To solve this, I first checked if the user exists in a Database. If yes then I simply need to update his points. Else I first need to insert his records.
After lot's of finding/debugging(literally 2 days 🤐), I came up with the following approach 😃
사용자에게 포인트 추가
def add_points(user_tag, username, msg_id, point, Is_helper):
mydb, cursor = get_connection()
query = """
SELECT username FROM Points WHERE user_tag = ?;
"""
value = (user_tag, )
cursor.execute(query, value)
check = cursor.fetchall()
if check:
# print('Already Present')
query = """
UPDATE Points SET total_points = total_points + ? WHERE user_tag = ?;
"""
values = (point, user_tag)
cursor.execute(query, values)
print(f'Updated Points for {username}! \n')
mydb.commit()
cursor.close()
mydb.close()
else:
query = """
INSERT INTO Points (user_tag, Username, message_id, total_points, Is_Helper) VALUES (?, ?, ?, ?, ?);
"""
values = (user_tag, str(username), msg_id, point, int(Is_helper))
cursor.execute(query, values)
print(f'Inserting the Record for {username}! \n')
mydb.commit()
cursor.close()
mydb.close()
사용자로부터 포인트 제거
def remove_points(user_tag, point):
mydb, cursor = get_connection()
query = """
SELECT Username FROM Points WHERE User_tag = ?;
"""
value = (user_tag, )
cursor.execute(query, value)
check = cursor.fetchall()
if check:
query = """
UPDATE Points SET Total_Points = Total_Points - ? WHERE User_Tag = ?;
"""
values = (point, user_tag)
cursor.execute(query, values)
print(f'Removed Points for {user_tag}! \n')
mydb.commit()
cursor.close()
mydb.close()
else:
print(f'User Does Not Exist! \n')
At last only 1 method needed to be created, To return single users points from the Database
def users_points(user_tag):
mydb, cursor = get_connection()
cursor.execute(""" SELECT total_points FROM Points WHERE user_tag = ?""", (user_tag, ))
row = cursor.fetchone()
return row
mydb.commit()
cursor.close()
mydb.close()
print('Fetching Data for users!\n')
이것은 End of the Database 부분을 만들고 Python과 연결하여 CRU(Create, Read, Update) 명령을 자동화합니다.
🖖🏼😃 이 블로그가 마음에 드시기 바랍니다!!! 🖖🏼😃
Reference
이 문제에 관하여(데이터베이스 스키마 및 Python 데이터베이스 함수 생성 👨🏼💻), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/megabarrel/creating-the-database-schema-and-python-database-functions-35kd
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
CREATE TABLE "Server_Info" (
"channel_name" VARCHAR(255),
"channel_id" BIGINT,
"server_name" VARCHAR(255)
);
CREATE TABLE "Points" (
"user_tag" INTEGER,
"username" VARCHAR(255),
"message_id" BIGINT,
"total_points" INTEGER,
"Is_Helper" BOOLEAN,
FOREIGN KEY("message_id") REFERENCES "Created_By"("message_id")
);
CREATE TABLE "Given_To" (
"ID" INTEGER AUTO INCREMENT,
"message_id" BIGINT,
"username" VARCHAR(255),
"user_id" BIGINT,
"user_tag" INTEGER,
"Is_Helper" BOOLEAN,
FOREIGN KEY("message_id") REFERENCES "Created_By"("message_id")
);
CREATE TABLE "Created_By" (
"ID" INTEGER AUTO INCREMENT,
"message_id" BIGINT,
"user_tag" INTEGER,
"username" VARCHAR(255),
"user_id" BIGINT,
"message_desc" VARCHAR(255),
"points_given" INTEGER,
"channel_name" VARCHAR(255),
"timestamp" DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY("message_id")
);
def get_connection():
mydb = sqlite3.connect('points.db')
cursor = mydb.cursor()
return mydb, cursor
def submitted_by(msg_id, usr_tag, username, user_id, msg_desc, points, channel_name):
mydb, cursor = get_connection()
query = """
INSERT INTO Created_By (message_id, user_tag, username, user_id, message_desc, points_given, channel_name) VALUES (?, ?, ?, ?, ?, ?, ?);
"""
values = (msg_id, int(usr_tag), str(username), user_id, str(msg_desc), points, str(channel_name))
cursor.execute(query, values)
mydb.commit()
cursor.close()
mydb.close()
print('Inserted Data Successfully to the Created_By Database!')
def server(channel_name, channel_id, server_name):
mydb, cursor = get_connection()
query = """
INSERT INTO Server_Info (channel_name, channel_id, server_name) VALUES (?, ?, ?);
"""
values = (channel_name, channel_id, server_name)
cursor.execute(query, values)
mydb.commit()
cursor.close()
mydb.close()
print('Inserted Data Successfully to the Server Database!')
def Given_To(msg_id, username, user_id, user_tag, Is_helper):
mydb, cursor = get_connection()
query = """
INSERT INTO Given_To (message_id, username, user_id, user_tag, Is_Helper) VALUES (?, ?, ?, ?, ?);
"""
values = (msg_id, str(username), user_id, int(user_tag), Is_helper)
cursor.execute(query, values)
mydb.commit()
cursor.close()
mydb.close()
print('Inserted Data Successfully to the Given_to Database!')
After some try/error method, I found out that the user points should be updated when points are given to them multiple times.
To solve this, I first checked if the user exists in a Database. If yes then I simply need to update his points. Else I first need to insert his records.
After lot's of finding/debugging(literally 2 days 🤐), I came up with the following approach 😃
def add_points(user_tag, username, msg_id, point, Is_helper):
mydb, cursor = get_connection()
query = """
SELECT username FROM Points WHERE user_tag = ?;
"""
value = (user_tag, )
cursor.execute(query, value)
check = cursor.fetchall()
if check:
# print('Already Present')
query = """
UPDATE Points SET total_points = total_points + ? WHERE user_tag = ?;
"""
values = (point, user_tag)
cursor.execute(query, values)
print(f'Updated Points for {username}! \n')
mydb.commit()
cursor.close()
mydb.close()
else:
query = """
INSERT INTO Points (user_tag, Username, message_id, total_points, Is_Helper) VALUES (?, ?, ?, ?, ?);
"""
values = (user_tag, str(username), msg_id, point, int(Is_helper))
cursor.execute(query, values)
print(f'Inserting the Record for {username}! \n')
mydb.commit()
cursor.close()
mydb.close()
def remove_points(user_tag, point):
mydb, cursor = get_connection()
query = """
SELECT Username FROM Points WHERE User_tag = ?;
"""
value = (user_tag, )
cursor.execute(query, value)
check = cursor.fetchall()
if check:
query = """
UPDATE Points SET Total_Points = Total_Points - ? WHERE User_Tag = ?;
"""
values = (point, user_tag)
cursor.execute(query, values)
print(f'Removed Points for {user_tag}! \n')
mydb.commit()
cursor.close()
mydb.close()
else:
print(f'User Does Not Exist! \n')
At last only 1 method needed to be created, To return single users points from the Database
def users_points(user_tag):
mydb, cursor = get_connection()
cursor.execute(""" SELECT total_points FROM Points WHERE user_tag = ?""", (user_tag, ))
row = cursor.fetchone()
return row
mydb.commit()
cursor.close()
mydb.close()
print('Fetching Data for users!\n')
Reference
이 문제에 관하여(데이터베이스 스키마 및 Python 데이터베이스 함수 생성 👨🏼💻), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/megabarrel/creating-the-database-schema-and-python-database-functions-35kd텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)