import pyodbc
cnxn_str = ("Driver={ODBC Driver 17 for SQL Server};"
"Server=#.#.#.#;"
"Database=DataBase;"
"PORT=1433;"
"UID=xxx;"
"PWD=xxx;")
cnxn = pyodbc.connect(cnxn_str)
//connect to sql database using connection string
cursor = cnxn.cursor()
sn_query ="SELECT **"
cursor.execute(sn_query)
//execute the select query
for row in cursor:
num= row[0]
print(num)
cursor = cnxn.cursor()
//execute the insert query
insert_bool_query ="INSERT into Table(name) values("The name you wan to insert");
cursor.execute(insert_bool_query)
for row in cursor:
print(row)
So I want to know whether if I can execute Select query, insert query and update query using only cursor.execute. In addition, if yes, then how to extract the rows for each query?
Related
I have a python script which connects to sql server instance. I running a cte query to remove duplicates. The query run sucessfully but when i used the fetchall() function it results in an Error: the previous query is not a sql query and after checking in the db table for the duplicates, it shows the duplicate still exists. This is the same case with both pyodbc and sqlalchemy.
Code pyodbc:
import pyodbc
conn = pyodbc.connect(connection_string)
cursor = conn.cursor()
query = ''';with cte as
(
SELECT [ID], [TIME], ROW_NUMBER() OVER
(PARTITION BY [ID] order by [TIME] desc) as rn
from table
)delete from cte WHERE rn > 1'''
cursor.execute(query)
cursor.close()
conn.close()
Code for sqlalchemy:
from sqlalchemy import create_engine
from sqlalchemy.sql import text
import urllib
conn = urllib.parse.quote_plus(connection_string)
engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(conn))
query = '''with cte as
(
SELECT [ID], [TIME], ROW_NUMBER() OVER (PARTITION BY [ID] order by [TIME] desc) as rn
from table
)
delete from cte WHERE rn > 1'''
connect = engine.connect()
result = connect.execute(query)
if result.returns_rows:
print("Duplicates removed")
else:
print("No row is returned")
when i used the fetchall() function it results in an Error: the previous query is not a sql query
This is the expected behaviour. Although your query includes a SELECT as part of the CTE, the query itself is ultimately a DELETE query which does not return rows. It will return a row count that you can retrieve with Cursor#rowcount, but Cursor#fetchall() will throw an error because there are no rows to retrieve.
I am trying to query MS SQL Server for a table.column, then insert this output into a sqlite table.
This example has one numeric column in the SQL Server source table.
I think I've almost got it by scouring the other answers.
Please let me know what I am missing.
import sqlite3
import pyodbc
#def connect_msss():
ODBC_Prod = ODBC_Prod
SQLSN = SQLSN
SQLpass = SQLpass
conn_str = ('DSN='+ODBC_Prod+';UID='+SQLSN+';PWD='+SQLpass)
conn = pyodbc.connect(conn_str)
#def connect_sqlite():
sl3Conn = sqlite3.connect('server_test.db')
c = sl3Conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS mrn_test (PTMRN NUMERIC)')
#def query_msss():
cur = conn.cursor()
cur.execute("SELECT TOP 50 PTMRN FROM dbo.atl_1234_mrntest")
rows = cur.fetchall()
for row in rows:
c.execute("INSERT INTO mrn_test VALUES (?)", row)
conn.commit()
#connect_msss()
#connect_sqlite()
#query_msss()
Error 1:
c.execute('CREATE TABLE IF NOT EXISTS mrn_test
(PTMRN NUMERIC)')
Out[117]: <sqlite3.Cursor at 0x2d1a742fc70>
Error 2:
cur = conn.cursor() cur.execute("SELECT TOP 50 PTMRN FROM
dbo.atl_1234_mrntest")
Out[118]: <pyodbc.Cursor at 0x2d1a731b990>
You're not committing the executed changes on the sqlite connection, after the c.execute step you're committing the MySQL DB connection. I think you need to replace conn.commit() at the end with sl3Conn.commit().
I am working with a SQL Database on Python. After making the connection, I want to use the output of one query in another query.
Example: query1 gives me a list of all tables in a schema. I want to use each table name from query1 in my query2.
query2 = "SELECT TOP 200 * FROM db.schema.table ORDER BY ID"
I want to use this query for each of the table in the output of query1.
Can someone help me with the Python code for it?
Here is a working example on how to do what you are looking to do. I didn't look up the schemes for the tablelist, but you can simply substitute the SQL code to do so. I just 'faked it' by unioning a statement of 2 tables. There are plenty of other answer on that SQL code and I don't want to clutter this answer:
How do I get list of all tables in a database using TSQL?
It looks like the key part you may have been missing was the join step to build the second SQL statement. This should be enough of a starting point to craft exactly what you are looking for.
import pypyodbc
def main():
table_list = get_table_list()
for table in table_list:
print_table(table)
def print_table(table):
thesql = " ".join(["SELECT TOP 10 businessentityid FROM", table])
connection = get_connection()
cursor = connection.cursor()
cursor.execute(thesql)
for row in cursor:
print (row["businessentityid"])
cursor.close()
connection.close()
def get_table_list():
table_list = []
thesql = ("""
SELECT 'Sales.SalesPerson' AS thetable
UNION
SELECT 'Person.BusinessEntity' thetable
""")
connection = get_connection()
cursor = connection.cursor()
cursor.execute(thesql)
for row in cursor:
table_list.append(row["thetable"])
cursor.close()
connection.close()
return table_list
def get_connection():
'''setup connection depending on which db we are going to write to in which environment'''
connection = pypyodbc.connect(
"Driver={SQL Server};"
"Server=YOURSERVER;"
"Database=AdventureWorks2014;"
"Trusted_Connection=yes"
)
return connection
main ()
I am trying something like:
import pyodbc
cnxn = pyodbc.connect(driver ='{SQL Server}' ,server ='host-MOBL\instance',database ='dbname', trusted_connection = 'yes' )
cursor = cnxn.cursor()
cursor.execute("""SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = N'TableName'""")
def checkTableExists(cnxn, TableName):
cursor = cnxn.cursor()
cursor.execute("""
SELECT COUNT(*)
FROM information_schema.tables
WHERE TABLE_NAME = '{0}'
""".format(TableName.replace('\'', '\'\'')))
if cursor.fetchone()[0] == 1:
cursor.close()
return True
cursor.close()
return False
if checkTableExists == True:
print ("already")
elif checkTableExists == False:
print ("No")
But there is nothing happen, can anyone help me on this?
I am using Micrsoft SQL Server Management Studio 2014 Express version.
The code will be run in Python.
Thank you
Use the built-in Cursor.tables method for this check - following code sample assumes connection and cursor are instantiated
if cursor.tables(table='TableName', tableType='TABLE').fetchone():
print("exists")
else:
print("doesn't exist")
Note this isn't functionally different from querying INFORMATION_SCHEMA.TABLES, but allows code portability with different database platforms (and IMO improves readability).
Using SQL Server Native Client 11.0 and SQL Server 2014, calling Cursor.tables just executes the sp_tables system stored procedure.
Here's a simple example:
import pyodbc
conn = pyodbc.connect('DRIVER={FreeTDS};SERVER=yourserver.com;PORT=1433;DATABASE=your_db;UID=your_username;PWD=your_password;TDS_Version=7.2;')
cursor = conn.cursor()
cursor.execute("""
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'your_table_name')
BEGIN
SELECT 'Your table exists.' AS result
END
""")
rows = cursor.fetchall()
for row in rows:
print(row.result)
That prints "Table Exists" for me. You should be able to modify it to your needs.
Using python and MySQLdb, how can I check if there are any records in a mysql table (innodb)?
Just select a single row. If you get nothing back, it's empty! (Example from the MySQLdb site)
import MySQLdb
db = MySQLdb.connect(passwd="moonpie", db="thangs")
results = db.query("""SELECT * from mytable limit 1""")
if not results:
print "This table is empty!"
Something like
import MySQLdb
db = MySQLdb.connect("host", "user", "password", "dbname")
cursor = db.cursor()
sql = """SELECT count(*) as tot FROM simpletable"""
cursor.execute(sql)
data = cursor.fetchone()
db.close()
print data
will print the number or records in the simpletable table.
You can then test if to see if it is bigger than zero.