comandante_ss
@comandante_ss

Как на Python добавить список в таблицу SQLite3?

Я получаю историю пользователя как список с словарями
[{trans:1,trans:2},{trans:1,trans:2}] - пример
И мне нужно ввести в таблицу sqlite3
Исходник

class Database:
	"""docstring for Database"""
	def __init__(self, db_name):
		self.connection = sqlite3.connect(db_name)
		self.cursor = self.connection.cursor()



	def add_user(self, user_id):
		with self.connection:
			def set_default(obj):
				if isinstance(obj, set):
					return list(obj)
				raise TypeError

			history = [{1,2},{3,4,5}]
			self.cursor.execute("INSERT INTO `users` ('user_id','history') VALUES (?,?)", (user_id,history))
			sell = self.cursor.execute("SELECT `history` FROM `users` WHERE `user_id` = ?", (user_id,)).fetchmany(1)

				print(sell)
				
				print(sell[0])
				print(sell[0][1])


Попытался сделать с помощью json, но в ячейку всё равно вносится строка, мне это не подходит
с json

class Database:
	"""docstring for Database"""
	def __init__(self, db_name):
		self.connection = sqlite3.connect(db_name)
		self.cursor = self.connection.cursor()
	def add_user(self, user_id):
		with self.connection:
			def set_default(obj):
				if isinstance(obj, set):
					return list(obj)
				raise TypeError

			history = json.dumps(list([{1,2},{3,4,5}]), default=set_default)
			

			self.cursor.execute("INSERT INTO `users` ('user_id','history') VALUES (?,?)", (user_id,history))
			sell = self.cursor.execute("SELECT `history` FROM `users` WHERE `user_id` = ?", (user_id,)).fetchmany(1)
			print(sell)
			
			print(sell[0][0])



Вывод: '[[1, 2], [3, 4, 5]]' а это str
Хочу найти +- элегантное решение
  • Вопрос задан
  • 586 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы