Home > Back-end >  How can I access a SQL file while using python?
How can I access a SQL file while using python?

Time:12-25

Right now I'm using Microsoft SQL Community to start a database, but for some reason I can't command the server to do something that I want, is there any to use the library sqlite3 or pyodc to print a value that I want on the console?

PYTHON:

connection = sqlite3.connect("REPLICATED_STORAGE.db")
cursor = connection.cursor()

sql_file = open("Template.sql")
sql_as_string = sql_file.read()
cursor.executescript(sql_as_string)

for row in cursor.execute("SELECT * FROM FRUITS"):
    print(row)

SQL:

USE [REPLICATED_STORAGE]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[FRUITS](
    [COLOR] [nchar](10) NOT NULL,
    [TYPE] [nchar](10) NULL,
    [NAME] [nchar](10) NULL,
    [WEIGHT] [nchar](10) NULL
) ON [PRIMARY]
GO

CodePudding user response:

sqlite3 talks to SQLite databases.

If you want to talk to a Microsoft SQL Server, Microsoft recommends using pyodbc. Follow the instructions to connect and run queries and the pyodbc documentation. To execute queries from a file, read the contents of the file and run it like any other query.

Note that executescript is specific to sqlite3. Use execute.

  • Related