I have a postgres username that contains a hyphen (example: 'user-1').
The following code works with python 2.6.3, but not with Python 2.7.10 :: Anaconda 1.9.2 (64-bit). I tried both single and double quotes around the username.
Any ideas?
username = 'user-1'
try:
con = psycopg2.connect(
database = database,
user = username,
password = password,
host = hostname
)
except:
print "I am unable to connect to the database."
The code errors with:
"/usr/local/apps/python/anaconda-current/lib/python2.7/site-packages/psycopg2/init.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) psycopg2.OperationalError: FATAL: password authentication failed for user "user-1
Related
I am trying to read the database of my MariaDB server. I have set it up like this:
CREATE DATABASE database1;
CREATE USER RaspberryPi#'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON database1.* TO RaspberryPi#'%';
SELECT database1;
CREATE TABLE Users;
This is on my Raspberry Pi 4 with the IP: 192.168.0.92. Now I have This Python script on my Windows computer:
import mysql.connector
mydb = mysql.connector.connect(host="192.168.0.92", user="RaspberryPi", passwd="password", database="database1")
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM Users")
print(mycursor)
Now I convert my Python script to an .exe file using pyinstaller. My problem is, that if I give this file to some other people, he can easily convert the .exe file to his original .py file and then he has my login credentials. Can I code it somehow, that the username and password isn't shown or the script can't be converted back?
Thanks.
you can use this snipet:
Module Imports
import mariadb
import sys
# Connect to MariaDB Platform
try:
conn = mariadb.connect(
user="db_user",
password="db_user_passwd",
host="192.0.2.1",
port=3306,
database="employees"
)
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)
# Get Cursor
cur = conn.cursor()
for more reference use this - https://mariadb.com/resources/blog/how-to-connect-python-programs-to-mariadb/
Update:
in order to make it more secure you can put the username and password with get input
I am trying to connect to psql server but unfortunately always receiving this error. (windows, vs code, python 3.7.4, psycopg2, postgresql 11)
Code part:
import psycopg2
import json
data = json.load(open("data.json"))
conn = psycopg2.connect(database = "dictfly", user = "postgres", password = "postgres", host = "127.0.0.1", port = "5432")
print("Opened database successfully")
cur = conn.cursor()
for pair in data:
cur.execute("ISERT INTO dict_tables VALUES (pair, data[pair])")
conn.commit()
print("Records created successfully")
conn.close()
Terminal
PS C:\mysite\dict> python jsonTOpgsql.py
Traceback (most recent call last):
File "jsonTOpgsql.py", line 6, in <module>
conn = psycopg2.connect(database = "dictfly", user = "postgres", password = "postgres0208", host = "127.0.0.1", port = "5432")
File "C:\Users\uafir\AppData\Local\Programs\Python\Python37-32\lib\site-packages\psycopg2\__init__.py", line 126, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError
PS C:\mysite\dict>
Thank you in advance!
I believe 'database' is not a valid keyword argument for psycopg2.connect(). Try using the keyword 'dbname' instead:
conn = psycopg2.connect(dbname="dictfly", user = "postgres", password = "postgres", host = "127.0.0.1", port = "5432")
Source: psycopg2 documentation
I'm trying to connect to a SQL Server DB from Python using pyodbc. I keep getting the error:
SyntaxError: unexpected character after line continuation character
I can't seem to figure out why. The DB is held on SQL Server 2012.
I'm new to Python, so if I'm making an egregiously silly error I apologize. So far, I've tried adding a ';' after the password and after the final parentheses. I've tried using {SQL Server} rather than {SQL Server Native Client 11.0}. I've changed Trusted Connection to yes as well. There is a username and password on the DB so I to use both.
import pyodbc
cnxn = pyodbc.connect(Driver = '{SQL Server Native Client 11.0}', Host = Name-DA\\SQLEXPRESS, database = TestDB, Trusted_Connection = tcon, username = user, password = pwd)
cursor = cnxn.cursor()
cursor.execute("select * from dbo.ProFormaData")
The error reads:
cnxn = pyodbc.connect(Driver = '{SQL Server Native Client 11.0}', Host
= Name-DA\SQLEXPRESS, database = DBName, Trusted_Connection = tcon, username = user, password = pwd)
^ SyntaxError: unexpected character after line continuation character
Process returned 1 (0x1) execution time : 0.075 s Press
any key to continue . . .
Hoping to just print out the data for now. This is a test for more data manipulation later.
First of all, I know this question was asked/answered once here, but I followed the steps suggested here, and got stucked in the middle of the steps.
Before the question, I have a Python script which runs well on a CentOS server:
import pyodbc
server = 'tcp:192.168.1.1'
database = 'MYDB'
username = 'username'
password = 'password'
sqlQuery = "SELECT * FROM dbo.DB1;"
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute(sqlQuery)
The same script gives me error on macOS, so I followed the nstruction in the previous link step by step, I had FreeTDS installed, and tested with tsql -S 192.168.1.1 -U username -P password. Things were fine so far.
Then I installed unixODBC with brew install unixodbc, and did the configuration as suggested:
/usr/local/Cellar/unixodbc/2.3.4/etc/odbcinst.ini
[FreeTDS]
Description=FreeTDS Driver for Linux & MSSQL on Win32
Driver=/usr/local/lib/libtdsodbc.so
Setup=/usr/local/lib/libtdsodbc.so
UsageCount=1
and..
/usr/local/Cellar/unixodbc/2.3.4/etc/odbc.ini
[MYSERVER]
Description = Test to SQLServer
Driver = FreeTDS
Trace = Yes
TraceFile = /tmp/sql.log
Database = 'MYDB'
Servername = 'tcp:192.168.1.1'
UserName = 'username'
Password = 'password'
Port = 1433
Protocol = 8.0
ReadOnly = No
RowVersioning = No
ShowSystemTables = No
ShowOidColumn = No
FakeOidIndex = No
Then I tested..
$ isql -v MYSERVER
[S1000][unixODBC][FreeTDS][SQL Server]Unable to connect to data source
[08S01][unixODBC][FreeTDS][SQL Server]Unable to connect: Adaptive Server is unavailable or does not exist
[01000][unixODBC][FreeTDS][SQL Server]Unknown host machine name.
[ISQL]ERROR: Could not SQLConnect
also..
$ isql -v tcp:192.168.1.1 username password
[IM002][unixODBC][Driver Manager]Data source name not found, and no default driver specified
[ISQL]ERROR: Could not SQLConnect
Back to my python script on macOS, I changed a little bit, and still could not connect to SQL server..
cnxn = pyodbc.connect('DRIVER=FreeTDS;SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute(sqlQuery)
Any ideas?
Here's the relevant part of my code:
try:
if self.pass_entry.get():
self.connection = pymysql.connect(
host=self.host_entry.get(),
user=self.user_entry.get(),
password=self.pass_entry.get(),
db=self.db_entry.get(),
charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor
)
else:
self.connection = pymysql.connect(
host=self.host_entry.get(),
user=self.user_entry.get(),
db=self.db_entry.get(),
charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor
)
except Exception as e:
self.console.insert(tk.END, "Error: {err}\n".format(err=str(e)))
Here's the error:
Connecting to 127.0.0.1...
Error: (1045, "Access denied for user 'root'#'localhost' (using password: YES)")
There's no password on "root" here, and PyMySQL is supposing that it has one. How can I connect without using a password? (I've tried to omit the password option when the password field / string is empty, but PyMySQL doesn't take it into account).
When there is no password for the database you need to pass "" to the function as password.
Try this in your else:
else:
self.connection = pymysql.connect(
host=self.host_entry.get(),
user=self.user_entry.get(),
password="",
db=self.db_entry.get(),
charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor
)
I had the same problem while using mysql.connector library.
Got around it by simply creating a new connection-user in addition to root.
After googling for a while it seemed like the access to root could be the problem, but I dropped looking further into it after I found the mentioned solution.
The user has the same settings in MySQL as root#localhost.
def mySQLcnx(someVariable):
dbCnx = mysql.connector.connect(host="localhost", user="pythonCnx", database="someDatabase")
dbCnxCursor = dbCnx.cursor()
dbCnxCursor.execute(someStatement)
DbQueryResults = dbCnxCursor.fetchall()