Pyodbc: Unable to update table on database (no error) - python

I have:
import pyodbc
con_str = "DRIVER={%s};SERVER=%s;UID=%s;PWD=%s;DATABASE=%s" % \
('FreeTDS','192.168.1.22','myuser','mypass','mydb')
con = pyodbc.connect(con_str)
cur = con.cursor()
cur.execute("update mytable set name='abcd'")
con.commit()
con.close()
The code executes and exits without any error !
But the database remains unchanged - nothing happened.

Resolved..
The problem was in the FreeTDS driver that I used.
I ran the same script on a windows machine using its native SQL Server Native Client 10.0 driver.
And it worked GREAT !

Related

Python & MySQL mysql.connector.errors.InterfaceError: 2013: Lost connection to MySQL server during query

I'm trying to use import mysql.connector to SELECT * from a table with ~1.9million rows in a remote database.
When I run the same query using the mysql cli client everything works just fine so I don't believe the issue is network or serverside. I've tried increasing connection_timeout to ridiculous numbers, but I still run into mysql.connector.errors.InterfaceError: 2013: Lost connection to MySQL server during query
Any ideas what to try next?
import mysql.connector
mydb = mysql.connector.connect(
host="mysql.prod.example.com",
user="user",
password="pass",
database="db",
auth_plugin='mysql_native_password',
connection_timeout=1000000
)
mycursor = mydb.cursor(dictionary=True)
mycursor.execute("SELECT * FROM table")
update_list = []
for row in mycursor:
row_id = row["id"]
row_ip = row["ip"]
print("IP: "+row_ip)
newlist = [row_id,row_ip,"/128"]
update_list.append(newlist)
Switching from Python2 to 3 solved my problem.
- #!/usr/bin/python
+ #!/usr/bin/python3

How do I overcome this sql connectivity error with python?

I am not able to connect to MySQL sever using python it gives and error which says
MySQLdb._exceptions.OperationalError: (1130, "Host 'LAPTOP-0HDEGFV9' is not allowed to connect to this MySQL server")
The code I'm using:
import MySQLdb
db = MySQLdb.connect(host="LAPTOP-0HDEGFV9", # your host, usually localhost
user="root", # your username
passwd="abcd13de",
db="testing") # name of the data base
cur = db.cursor()
cur.execute("SELECT * Employee")
for row in cur.fetchall():
print(row[0])
db.close()
This is an authorization problem not a connectivity problem. Is the db running locally? If not, confirm with the admin where it is hosted. If so, try changing the host parameter to 127.0.0.1?
As described here the admin can get the hostname by running:
select ##hostname;
show variables where Variable_name like '%host%';
If the connection was timing out you could try setting the connect_timeout kwarg but that's already None by default.

Pymysql Windows Authentication Error

I am attempting to connect to SQL Server Management Studio. My code is below and returns the error: "init() got an unexpected keyword argument 'trusted'." I am using pymysql, would like to connect using Windows Authentication, and am running on 64 bit windows machine. Any help would be appreciated.
Edit - removed trusted. Error I am now receiving is 'No connection could be made because the target machine actively refused it'
import pymysql
import pymysql.cursors
conn = pymysql.connect(host = 'DESKTOP-6CIMC97')
Have you checked out the example on GitHub? trusted doesn't seem to be required.
https://github.com/PyMySQL/PyMySQL/blob/master/example.py
#!/usr/bin/env python
from __future__ import print_function
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='mysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
print(cur.description)
print()
for row in cur:
print(row)
cur.close()
conn.close()

Pymysql Insert Into not working

I'm running this from PyDev in Eclipse...
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='userid', passwd='password', db='fan')
cur = conn.cursor()
print "writing to db"
cur.execute("INSERT INTO cbs_transactions(leagueID) VALUES ('test val')")
print "wrote to db"
The result is, at the top of the Console it says C:...test.py, and in the Console:
writing to db
wrote to db
So it's not terminating until after the execute command. But when I look in the table in MySQL it's empty. A record did not get inserted.
First off, why isn't it writing the record. Second, how can I see a log or error to see what happened. Usually there should be some kind of error in red if the code fails.
Did you commit it? conn.commit()
PyMySQL disable autocommit by default, you can add autocommit=True to connect():
conn = pymysql.connect(
host='localhost',
user='user',
passwd='passwd',
db='db',
autocommit=True
)
or call conn.commit() after insert
You can either do
conn.commit() before calling close
or
enable autocommit via conn.autocommit(True) right after creating the connection object.
Both ways have been suggested from various people at a duplication of the question that can be found here: Database does not update automatically with MySQL and Python

Connecting python 3.3 to microsoft sql server 2008

I am new to python. I am using Pydev IDE with Eclipse for python programming in my Windows machine. I am using python 3.3 vern and want to connect with MS Sql Server 2008. Could someone suggest how should I connect with MS Sql Server 2008.
I will augment mata's answer with a pypyodbc example.
import pypyodbc
connection_string ='Driver={SQL Server Native Client 11.0};Server=<YOURSERVER>;Database=<YOURDATABASE>;Uid=<YOURUSER>;Pwd=<YOURPASSWORD>;'
connection = pypyodbc.connect(connection_string)
SQL = 'SELECT * FROM <YOURTABLE>'
cur = connection.cursor()
cur.execute(SQL)
cur.close()
connection.close()
pyodbc supports python3 and can connect to any databas for wich there's an odbc driver, including sql server.
There's also a pure python implementation pypyodbc which also should supoort python3.
adodbapi also claims to work with python3.
Here you can find a list with some more options.
import pyodbc
server = 'SERVIDORNOMEOUIP'
database = 'MEUBANCO'
username = 'USERSQL'
password = 'SENHASQL'
#for SQL Server 2008
driver='{SQL Server Native Client 10.0}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password + ';')
cursor = cnxn.cursor()
cursor.execute("SELECT nome,senha FROM [tabusuariosenha]")
row = cursor.fetchone()
print ("CAMPO1 | CAMPO2 " )
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()

Categories