skip to Main Content

Is there a way to lint SQLite commands contained within a .execute() method call for a database connection object (from Python’s sqlite3 library) from within Visual Studio Code? I’ve seen this done in Intellij IDEA but this is not my preference IDE. I should also note that I am using Pylance as my linter.

I’ve tried searching the settings of Visual Studio Code, specifically under the Python Linter settings, but this has produced no leads.

2

Answers


  1. You have to install mysql-connector-python package:

    pip install mysql-connector-python
    

    Then create a Python script to connect to the database, and I can give you a simple example which uses the select statement and print line by line:

    import mysql.connector
    
    conn = mysql.connector.connect(
        host="localhost",
        database="dbname",
        user="user",
        password="password")
    
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM table")
    
    for row in cursor:
        print(row)
    
    Login or Signup to reply.
  2. You can use command pip install cs50 in terminal to install cs50 package.

    Then you can use codes db = cs50.SQL("sqlite:///file.db") # For SQLite, file.db must exist to connect the SQLite.

    There exists .execute method as well.

    The example in the document of cs50 can help you better understand:

    import cs50
    
    db = cs50.SQL("sqlite:///file.db")
    
    rows = db.execute("SELECT * FROM foo")
    
    rows = db.execute("SELECT * FROM foo WHERE bar = ? AND baz = ?", 1, 2)
    rows = db.execute("SELECT * FROM foo WHERE bar IN (?) AND baz IN (?)", [1, 2], [3, 4])
    
    rows = db.execute("SELECT * FROM foo WHERE bar = :bar AND baz = :baz", bar=1, baz=2)
    rows = db.execute("SELECT * FROM foo WHERE bar IN (:bar) AND baz IN (:baz)", bar=[1, 2], baz=[3, 4])
    
    id = db.execute("INSERT INTO foo (bar, baz) VALUES(?, ?)", 1, 2)
    id = db.execute("INSERT INTO foo (bar, baz) VALUES(:bar, :baz)", bar=1, baz=2)
    
    n = db.execute("UPDATE foo SET bar = ?, baz = ?", 1, 2)
    n = db.execute("UPDATE foo SET bar = :bar, baz = :baz", bar=1, baz=2)
    
    n = db.execute("DELETE FROM foo WHERE bar = ? AND baz = ?", 1, 2)
    n = db.execute("DELETE FROM foo WHERE bar = :bar AND baz = :baz", bar=1, baz=2) 
    

    The syntax error display of SQL statements is not supported for Pylance. You can read this issue on github for the reason. At present, there are no similar extensions in the market to meet this requirement. You have to check the correctness of the SQL statements yourself.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search