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.
Related
I am using mysql.connector in Python to manage particular database, I am trying to check in a table if there is any tuple or row that meet a condition, here is the code:
db_campaign = mysql.connector.connect(
host="localhost",
user="root",
passwd="pass",
database="campaign"
)
cursor = db_campaign.cursor()
query = "SELECT EXISTS(SELECT * FROM transaction WHERE id = 10)"
cursor.execute(query)
for val in cursor:
if val[0] == 1:
found = True
Is there any way to make this cleaner?
cursor = db_campaign.cursor()
query = "SELECT 1 FROM transaction WHERE id = 10)"
cursor.execute(query)
return cursor.fetchone() is not Non
You can also test len(cursor.fetchall())
I have a SQL-file (SQLite format 3) that I can query with the DB Browser for SQLite (Windows). Whenever I use Python to access the db I get a Null result.
import sqlite3
conn = sqlite3.connect('C:/tmp/test.sql')
cursor = conn.cursor()
conn.execute('select count(*) from Player')
print("result is:", cursor.fetchone()) # result is: None
Every Select statement leads to "result is: None".
Any ideas?
Bart.
import sqlite3
connection = sqlite3.connect(database_name)
cursor = connection.cursor()
cursor.execute("select val from table_name where x = 'something';")
result = cursor.fetchone()
# directly returning result also gives null
if result:
return result[0] # tuple returned in result
cursor.close()
connection.close()
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 have this great pyodbc lib. I try the code below, it supposed to insert a row and return the row id but it didn't work. by the way I'm using sql server 2005 on server and client is windows os
...
con = pyodbc.connect('conectionString', autocommit = True)
cur = con.execute(
"insert into sometable values('something');
select scope_identity() as id"
)
for id in cur:
print id
...
some idea?
Try this, one statement with the OUTPUT clause
cur = con.execute(
"insert into sometable OUTPUT INSERTED.idcolumn values('something')"
)
row = cur.fetchone()
lastrowid = row[0]
Edit: This should get around the issue commented by Joe S.
Using SCOPE_IDENTITY() is the way to go as there are limitations and quirks using OUTPUT and ##IDENTITY because of triggers.
Using your code snipped, you just need to add a call to nextset to get the id.
...
con = pyodbc.connect('conectionString', autocommit = True)
cur = con.execute(
"insert into sometable values('something');
select scope_identity() as id"
)
cur.nextset()
for id in cur:
print id
...
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.