S
S
SerjLore2020-10-04 20:29:08
Python
SerjLore, 2020-10-04 20:29:08

When selecting data in sqlite3 and with fetchone, None comes out, although everything is fine in the db browser?

Hello, I ran into the problem of displaying and using data from the db, everything is displayed normally in the "DB Browser for SQlite" program, but when executing the code in fetchone() = None ..
Please help.

The code itself:

import discord
from discord.ext import commands
import os
import asyncio 
from time import strftime, sleep
from colorama import init
init()
from colorama import Fore, Back, Style
import sqlite3

db = sqlite3.connect('bot.db')
sql = db.cursor()

sql.execute("""CREATE TABLE IF NOT EXISTS servers (
  log_id,
  administator,
  owner_guild_id,
  guild_id,
  test
  )""")
db.commit()

def get_pref(bot, message):
  default_prefix = '%'
  guildid = str(message.guild.id)
  print(guildid)
  sql.execute("SELECT test FROM servers WHERE guild_id = ?", (guildid,))
  if sql.fetchone() is not None:
    pref = sql.fetchone()
    print(pref)
    return pref

  else:
    print('Объект "None"')
    sql.execute("UPDATE servers set test = ?", (default_prefix))
    db.commit()

prefix = 'kek'
bot = commands.Bot(command_prefix = get_pref)
bot_author = 694867925634515045
#bot = commands.Bot(command_prefix = prefix)
bot.remove_command('help') # удаляет стартовую хелп команду бота
token = 'кек' # токен бота


Result in debug:
5f7a064cdc79b395242057.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
o5a, 2020-10-05
@SerjLore

The problem is here

if sql.fetchone() is not None:
    pref = sql.fetchone()

the fetchone() call completely fetches the data from the cursor, as a result, the subsequent fetchone() call returns null
You need to fetch into a variable, which you can use later:
pref = sql.fetchone()
if pref is not None:
    # использовать уже pref напрямую, а не sql.fetchone()

PS although I probably did not quite understand the problem, it seems that initially the data is not even selected, so the problem is still in something. But even after that, the above must be corrected, otherwise it will not give out the data either (but for the indicated reason).

R
Ruslan., 2020-10-04
@LaRN

Perhaps the reason is that you are creating the table incorrectly. You have specified only a list of fields, but for each field you also need to specify a type.
I'm talking about this code:
sql.execute("""CREATE TABLE IF NOT EXISTS servers (
log_id,
administator,
owner_guild_id,
guild_id,
test
)""")
db.commit()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question