问题
I query data from my "data.sqlite"'s database, run my project and get "sqlite3.OperationalError: no such table: blog_post". It would be great if you could help me fix this error. Thank you!
I created a table called "BlogPost", its table name as "blog_post" in the models.py:
class BlogPost(db.Model):
__tablename__ = 'blog_post'
users = db.relationship(User)
blog_id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer,db.ForeignKey('users.id'), nullable=False)
date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) #
problem_name = db.Column(db.String(140), nullable=False)
text = db.Column(db.Text, nullable=False)
blog_image = db.Column(db.String(140), nullable=False, server_default='default_blog.jpg')
def __init__(self, text, problem_name, user_id, blog_image):
self.text = text
self.problem_name = problem_name
self.user_id = user_id
self.blog_image = blog_image
def __repr__(self):
return f"Post ID: {self.post_id} -- Date:{self.date}---{self.problem_name}"
Using query console, I checked and see that this table is storing data just fine and I can see that there is no error.
I wanted to query data from this table and show it to the HTML file on my web page so I imported it with the command "myproject.models import BlogPost" into the python file called "views.py" (My Pycharm IDE show that the command is working fine and show no error)
Then I have these codes below:
from flask import render_template, request, Blueprint
import _sqlite3
...some other import
init_db()
conn = _sqlite3.connect('data.sqlite', check_same_thread=False)
c = conn.cursor()
core = Blueprint('core', __name__)
@core.route('/', methods=['GET', 'POST'])
def index():
search = Blogsearch_form(request.form)
if request.method == 'POST':
c.execute("SELECT * FROM blog_post WHERE problem_name LIKE (?)", ('%' + str(search) + '%',))
results = c.fetchall()
return render_template('blog_search_result.html', results=results)
Picture of my data.sqlite database:
I query to see the table blog_post in the console and it identified that the table name is blog_post. It also shows all the data I inputted in the website:
By the way, this is one of the code that I used to create my "data.sqlite" database inside my project's init.py:
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir,
'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
回答1:
When you do a request, you do it from a table.
Your command is:
c.execute("SELECT * FROM BlogPost WHERE problem_name LIKE (?)", ('%' + str(search) + '%',))
Your table name seems to be "blog_post" and not "BlogPost" like it is in your request.
I do not have the whole picture of your code so you could try and give the feedback.
you could write your code using format() command something like this to have access the tablename design in your model.
c.execute("SELECT * FROM {0} WHERE problem_name LIKE {1}".format(tablename, '%' + str(search) + '%')))
(tablename represents your tablename in your model used for creation)
Like the problem seems to be related to the path code is trying to access database :
1/ to know the current directory put here the print(os.getcwd()) command :
if request.method == 'POST':
print("current working path : ", os.getcwd())
c.execute("SELECT * FROM blog_post WHERE problem_name LIKE (?)", ('%' + str(search) + '%',))
2/ To test if connection works with the real rPath = '.../database'
conn = _sqlite3.connect(rPath, check_same_thread=False)
回答2:
I just fixed this! A lot of thanks to Laurent(comment up above) for helping me!
So I just moved the data.sqlite file to the outside, in the biggest folder. The error was because I wrote the wrong path in the importing command;)
But his or her codes also work so check that out!
Now it identified the table just fine:)
来源:https://stackoverflow.com/questions/61849700/my-python-file-cant-identify-my-sqlites-table-even-when-i-imported-it