pymssql utf8: queries with back slash - python

I'm a bit curious what is the pythonic/best way to solve my issue.
A short code example:
import pymssql
conn = pymssql.connect("SERVER", 'sa', 'PASSWORD', 'DATABASE', charset='utf8')
cursor = conn.cursor()
sql = "SELECT 'foo\bar' as bs_field"
cursor.execute(sql)
row = cursor.fetchone()
print row[0]
# missing \, returns u'foobar'
sql = "select FIELD_CONTAINING_BACKSLASH from TABLE"
cursor.execute(sql)
row = cursor.fetchone()
print row[0]
# all OK here
sql = "SELECT 'foo\\bar' as bs_field"
cursor.execute(sql)
row = cursor.fetchone()
print row[0]
# this is OK too
I want to know why the \ is missing in the first example - is there a better solution as quoting every single sql?

I am an idiot!
Has nothing to do with mssql, it's just python strings.
r'bla\bla'
'bla\\bla'
Reference: https://docs.python.org/2.0/ref/strings.html

Related

Is there any cleaner way to check if tuple or row are meet a condition in a database using mysql connector?

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())

Pyodbc- If table exist then don't create in SSMS

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.

python mysql select return only first row of table, not all

im dealing with strage problem and this is like this:
this query should return all of my table:
db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
cursor.execute("select * from mytable")
cursor.fetchall()
for row in cursor:
print row
for loop should print all rows in cursor but it will only print the first one.
it seems cursor is filled with first row only.
is there anything that i missed here?
thanks
You need to put the output of cursor.fetchall() into a variable. Like
db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
cursor.execute("select * from mytable")
rows = cursor.fetchall()
for row in rows:
print row
You can try limit:
cursor.execute("select * from mytable limit 1")
Try
db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
for row in cursor.execute("select * from mytable"):
print row
you need a dic and save the result here
dic={}
cursor.execute("select * from table")
dic['table']=cursor.fetchall()
for row in range(len(dic['table'])):
print dic['table'][row]
and if you need print any colum
print dic['table'][row]['colum']
This is not the correct way to use the .fetchall() method. Use cursor.stored_results() and then do a fetchall() on the results to perform this task, like this:
db = MySQLdb.connect(host="localhost", port=3306, user="A", passwd="B", db="X")
cursor = db.cursor()
cursor.execute("select * from mytable")
results = cursor.stored_results()
for result in results:
print result.fetchall()
I also had this problem. My mistake was that after inserting new row in the table I didn't commit the result. So you should add db.commit() after INSERT command.
i know its been very long time since, but i didnt find this answer anywhere else and thought it might help.
cursor.execute("SELECT top 1 * FROM my_table")

Can not see the DB query output in python

I'm execute a simple mssql query from python.
I can see in the profiler that the query reach the DB.
The query has 1 row of answer.
I fail to see the output in the Python shell
I run the code below
import pymssql
conn = pymssql.connect(host='SQL01', user='user', password='password', database='mydatabase', as_dict=True)
cur = conn.cursor()
cur.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
for row in cur:
print "ID=%d, Name=%s" % (row['id'], row['name'])
Pleas advise
Thanks,
Assaf
You can call fetchone() or fetchall() after execute to get the data from that query.
import pymssql
conn = pymssql.connect(host='SQL01', user='user', password='password', database='mydatabase', as_dict=True)
cur = conn.cursor()
cur.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
print cur.fetchall()
import pymssql
conn = pymssql.connect(host='SQL01', user='user', password='password', database='mydatabase', as_dict=True)
cur = conn.cursor()
users = cur.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe').fetchall()
conn.close()
for row in users:
print "ID=%d, Name=%s" % (row['id'], row['name'])
Try assigning the results to something instead of using the cursor.
cur.execute() is a function, as such while it does return a value (which you saw), you're not assigning it to anything, so when you go to do the for loop, there's nothing to loop over.
If you don't want to store the result, you could do this (rather messy) version:
import pymssql
conn = pymssql.connect(host='SQL01', user='user', password='password', database='mydatabase', as_dict=True)
cur = conn.cursor()
sql = 'SELECT * FROM persons WHERE salesrep=%s'
for row in cur.execute(sql, 'John Doe').fetchall():
print "ID=%d, Name=%s" % (row['id'], row['name'])
conn.close()
This one does the for loop over the result of the cur.execute(), but I really advise against this
(Minor addendum: I forgot the fetchall's, I'm so used to putting this in a function. Sorry)

is there a way to do a insert an request the scope_identity() using pyodbc to sql server 2005

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
...

Categories