nasrin begum pathan
nasrin begum pathan

Reputation: 53

How to connect to my SQL server from Py script?

I am trying to connect to SQL server from Py script and I tried the same code of my jupyternotebook but the page shows blank after I import pyodbc. Is there any other way I connect to my SQL server from Pyscript?

Here is the code which I tried.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Damp Brook</title>

    <!-- Recommended meta tags -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">

    <!-- PyScript CSS -->
    <link rel="stylesheet" href="https://pyscript.net/releases/2024.8.1/core.css">

    <!-- This script tag bootstraps PyScript -->
    <script type="module" src="https://pyscript.net/releases/2024.8.1/core.js"></script>
</head>
<body>
    <script type="py" src="./main.py" config="./pyscript.toml" terminal></script>
</body>
</html>

main.py

import pyodbc
import pandas as pd

conn_str = ("Driver={SQL Server};"
            ""
            "")
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
cursor.execute("SELECT  * FROM TestTable")
df = pd.DataFrame((tuple(t) for t in cursor))
print(df)

pyscript.toml

packages = ["pandas","pyodbc"]

Upvotes: 1

Views: 91

Answers (1)

Legendstyler
Legendstyler

Reputation: 11

Connecting directly to a SQL Server using pyodbc from a PyScript application is not feasible due to several limitations:

Pyodbc Compatibility: pyodbc is a C extension module that requires native system libraries. PyScript runs in the browser using Pyodide, which supports only pure Python packages or those specifically compiled for WebAssembly. pyodbc is not available in Pyodide's package repository and cannot be used in the browser environment.

Browser Limitations: Browsers do not support the necessary network protocols and sockets required to establish a direct connection to a SQL Server. Security restrictions prevent browsers from opening arbitrary network connections to protect users from malicious activities.

Security Concerns: Even if it were technically possible, exposing your database directly to client-side applications would pose significant security risks. It could allow unauthorized access to your database, leading to data breaches.

Upvotes: 1

Related Questions