Python Submit Scale to Database: File Reading and MySQL Call Notes

File Reading Module A classic recursion. Note that if the input is not an absolute path, it will search the current working directory (relative directory). python def dirnow:str: result=[] for i in os.listdirnow: if os.path.isdiri and i[:1] = '.': result += dirnow+'/'+i if ".json" in i: result += [now] return result This implements locating

File Reading Module

A classic recursion. Note that if the input is not an absolute path, it will search the current working directory (relative directory).

def dir(now:str):
	result=[]
	for i in os.listdir(now):
		if os.path.isdir(i) and i[:1] != '.':
			result += dir(now+'/'+i)
		if ".json" in i:
			result += [now]
	return result

This implements locating all .json files.

About Python's list.append()

If you append a dictionary afterwards, it will be appended in a form similar to a soft link:

res = []
tmp = {"A":"a, "B":"b"}
s = "Apple"
for i in s:
    tmp[i]=i
    res.append(tmp)

If you only need to change a small parameter, you can directly write the object into the function argument instead of creating a separate variable.

MySQL

Natural language programming master)

Load module

import mysql.connector
cnx = mysql.connector.connect(user='', password='', host='', database='')
# Check if the specified field exists
def has_scale(scale_id:int):
	cursor = cnx.cursor()
	select_query = """
		SELECT id FROM questionnaires
		WHERE id = %s
		LIMIT 1
	"""
	cursor.execute(select_query, (scale_id,))
	res = cursor.fetchone() is not None
	cursor.close()
	return res

# Insert when the field does not exist
def insert_scale(scale):
	cursor = cnx.cursor()
	insert_query = """
		INSERT INTO questionnaires (id, title, introduction, cid, res, options)
		VALUES (%s, %s, %s, %s, %s, %s)
	"""
	data = (scale["id"], scale["title"], scale["introduction"], scale["category"], str(scale["res"]), str(scale["options"]))
	cursor.execute(insert_query, data)
	cursor.close()

# Actually update will update all matching records, but I use the primary key as the condition
def update_scale(scale):
	cursor = cnx.cursor()
	update_query = """
	UPDATE questionnaires
	SET title = %s, introduction = %s, cid = %s, res = %s, options = %s
	WHERE id = %s
	"""
	data = (scale["title"], scale["introduction"], scale["category"], str(scale["res"]), str(scale["options"]),scale["id"])
	cursor.execute(update_query, data)
	cursor.close()
# Remember to commit and disconnect
def commit():
	cnx.commit()
	cnx.close()

It is worth noting that it seems that three " in Python can be written across lines) I haven't studied it carefully.

Comments

0

No comments yet.