I got the following code from this site to connect to a mysql database through python (which is much appreciated by the way). I have used it once already to connect to a database on the server, but in a different file. However I know want to connect to another database on the same server but i keep getting error message to do with the database name.
I am using exactly the same code as I was before to connect, however i have only changed the database name to the other one i want to connect to. I can look at the database through puTTY, and see that it is called the correct name and that all the data is there, but just cant seem to connect properly through the Python.
Thanks in advance for any help!
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect(host="127.0.0.1", # your host, usually localhost
user="root", # your username
passwd="........", # your password
db="opt_out") # name of the data base
# you must create a Cursor object. It will let
# you execute all the query you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("SELECT * FROM opted_in")
# print all the first cell of all the rows
for row in cur.fetchall() :
print row[0]
And this is the error code i get in return when i try and execute the python file through puTTY:
Traceback (most recent call last):
File "/var/www/html/vra/ConnectAdiDB.py", line 7, in <module>
db="opt_out") # name of the data base
File "/usr/lib64/python2.6/site-packages/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.6/site-packages/MySQLdb/connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (1045, "Access denied for user 'root'#'localhost' (using password: YES)")
The Password must be wrong (I Think so)
So Try to reset the password so:
first off turn of the mysql Service like so
Ubuntu/Debian:
sudo service mysql stop
After That Do So:
sudo service mysql start
When Done Start mysql like so:
sudo mysql
An execute:
UPDATE mysql.user SET Password=PASSWORD('NEW-PASSWORD') WHERE User='root';
FLUSH PRIVILEGES;
Related
I have created a python file app.py and included the code to connect to a db I created in postgresql as follows: -
import psycopg2
conn = psycopg2.connect(
user='postgres',
password='1234',
host='localhost',
port='5432',
database='bubbleformation'
)
cursor = conn.sursor()
cursor.execute('SELECT * FROM bubbleformation')
for row in cursor: print(row)
conn.close()
This was as instructed in this medium article
However, when I try to execute this python file in the terminal, I get the below error: -
Traceback (most recent call last): File "app.py", line 8, in
port='5432' File "/usr/lib/python2.7/dist-packages/psycopg2/init.py", line 130, in
connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: database "bubbleformation" does not exist
I have created a table named "bubbleformation" and it can be viewed in the psql mode through the terminal.
Could anyone please help me understand what should be done? I tried changing the password, and user privileges, but none of them worked for my error.
You should create both database and table with the same name "bubbleformation". You've probably created that table in postgres database.
Enter psql as postgres user and call CREATE DATABASE bubbleformation;, then connect to it with \connect bubbleformation and then create your table (something like CREATE TABLE bubbleformation (id int, name text);).
The error is about there not being a database named "bubbleformation", so when you connect to the database in the terminal, whichever database that is is the one you need to specify in the database parameter. When you connect to the database in the terminal, type:
SELECT current_database();
If it is indeed a database named "bubbleformation" then is must be a different cluster you are connecting to, and therefore a different port.
Disclosure: I am an EnterpriseDB (EDB) employee.
Its due to environment error. I was loading the credentials from the .env file. But i mistakenly gave a wrong path.
project_folder = os.path.expanduser('~/scraping') instead of
project_folder = os.path.expanduser('~/find_my_nearest_store')
load_dotenv(os.path.join(project_folder, '.env'))
Hence the Error.
I want to access a gdb file with python.
I'm new to firebird and interbase.
I can access my file with this command: (Debian 8.4)
isql-fb mydb.gdb
How can I connect to same file with Python?
I tried fdb and kinterbasdb and always get an error message:
I have tried these lines:
con = fdb.connect(dsn='/home/bruno/Desktop/mydb.gdb')
con = fdb.connect(dsn='localhost:/home/bruno/Desktop/mydb.gdb')
con = fdb.connect(dsn='/home/bruno/Desktop/mydb.gdb', user='SYSDBA', password='*****')
The error is always something like:
fdb.fbcore.DatabaseError: ('Error while connecting to database:\n- SQLCODE: -902\n- Your user name and password are not defined. Ask your database administrator to set up a Firebird login.', -902, 335544472)
Thank you for your help
Thank you all for your time.
I solved it changing sysdba password with gsec.
The password was ok in config file but not in security database.
I have two machines: local_machine, server_machine. I have mysql server on server_machine and sftp server on local_machine. I am trying to send sritest.csv file (UTF-8) from local_machine to server_machine using python. These are the contents of sritest.csv:
1,2,3
I have the sql query saved in sritest.sql and these are the contents of the file:
LOAD DATA INFILE '{}'
INTO TABLE TESTBED_STAGING.test
COLUMNS TERMINATED BY ','
;
This is the python script I have now:
import MySQLdb
import os
import string
# Open database connection
db = MySQLdb.connect (host="1.2.3.4",port=3306,user="app_1",\
passwd="passwd",db="TESTBED_STAGING")
cursor=db.cursor()
#Query under testing
sql = open('sritest.sql','r').read()
print sql
l = os.listdir(".")
for file_name in l:
if file_name.endswith('sritest.csv'):
print 'the csv file we are reading is: '+file_name
#try:
cursor = db.cursor()
print 'filename is '+sql.format(file_name)
cursor.execute(sql.format(file_name))
db.commit()
'''
except Exception:
# Rollback in case there is any error
db.rollback()
print 'ERROR - So, rollback :( :( '
'''
# disconnect from server
db.close()
In the above script, I commented try,except so I can see the error where it breaks. Currently the code is breaking at cursor.execute(sql.format(file_name)) line with this error:
OperationalError: (1045, "Access denied for user 'app_1'#'%' (using password: YES)")
I have been playing around but not able to fix it. Any suggestions/ideas?
For starters, creating cursor at every loop is not a good idea. You've already created a cursor earlier, so you can remove the cursor declaration in the for loop.
Second, I think your error is due to lack of access on MySQL server at 1.2.3.4 remotely using user app_1. Try this on the server's MySQL console,
GRANT ALL PRIVILEGES ON TESTBED_STAGING.* TO 'app_1'#'%';
Lastly, try and avoid using print "line" notation and start switching to the print("line") notation for compatibility with Python 3.x
I figured out the answer and decided to leave this question open for those who might face the similar problem:
In the MySQL server (server_machine), make sure you do this after you start mysql:
mysql>grant all privileges on *.* to 'app_1'#'%' identified by 'passwd';
change LOAD DATA INFILE '{}' in sritest.sql to LOAD DATA LOCAL INFILE '{}'
In the python code, edit the MySQLdb.connect statement as:
db = MySQLdb.connect (host="1.2.3.4",port=3306,user="app_1",\
passwd="passwd",db="TESTBED_STAGING", local_infile=1)
All errors are eliminated and data is transferred.
I am trying to access hive using pyhs2. I tried the following code:
example.py
import pyhs2
conn = pyhs2.connect(host='localhost', port=10000,authMechanism=None, user=None, password=None,database='default')
with conn.cursor() as cur:
cur.execute("select * from table")
for i in cur.fetch():
print i
I am getting the following error:
Traceback (most recent call last):
File "example.py", line 2, in <module> conn = pyhs2.connect(host='localhost', port=10000,authMechanism=None, user=None, password=None,database='default')
File "build/bdist.linux-x86_64/egg/pyhs2/__init__.py", line 7, in connect
File "build/bdist.linux-x86_64/egg/pyhs2/connections.py", line 46, in __init__
File "build/bdist.linux-x86_64/egg/pyhs2/cloudera/thrift_sasl.py", line 55, in open
File "build/bdist.linux-x86_64/egg/thrift/transport/TSocket.py", line 101, in open
thrift.transport.TTransport.TTransportException: Could not connect to localhost:10000
I am getting the exact error when I try with hive utils. I have checked sasl installation. Do I need to make any changes to the hive-site.xml in hive? If yes where do I need to create it? Am I missing out something?
1- Figure out the IP address of the localhost using (on Linux):
hostname -I
2- Change localhost to the actual ip
I would also suggest that you double check which host Hive is on. If you are using hortonworks, on Ambari, go to Hive, then Configs and check the host there.
Edit (adding another suggestion):
Your username and password most likely aren't None. To get your username and password, check hive-site.xml and look at the values in javax.jdo.option.ConnectionUserName and javax.jdo.option.ConnectionPassword. If you can't find anything, try an empty string as the password (as opposed to None), and hive or empty string as the username i.e. try these one by one:
conn = pyhs2.connect(host='localhost', port=10000,authMechanism='PLAIN', user='hive', password='',database='default')
conn = pyhs2.connect(host='localhost', port=10000,authMechanism='PLAIN', user='', password='',database='default')
Note that I also changed authMechanism to "PLAIN"
Just today I have decided that I wanted to learn python because I personally like the syntax and its feel. I am a pretty young developer and I really wanted to learn a new programming language since I am only fluent in JavaScript (especially javascript) and PHP so I decided on Python. Python seems quite like javascript execpt for the fact that they don't use curly braces to define a new block. And of course its far more powerful.
I've learned that you can connect to MySQL databases using MySQLdb .
But I am having an issue, when I use the following code.
db = MySQLdb.connect(host="localhost", user="methodjs_postes", passwd="********", db="methodjs_postes");
I get this large error:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
db = MySQLdb.connect(host="localhost", user="methodjs_postes", passwd="********", db="methodjs_postes");
File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")
The main part that I was really focusing on though was the Can't connect to MySQL server on 'localhost' (10061) part. (But it would be nice if you explain the other parts too)
I don't see why i'm getting this issue.
I use localhost in my PHP and it works just fine. And I did import the MySQLdb which I don't think is the error because then it wouldn't even attempt to connect.
I am using python 2.7, I would be using 3.3 (have it downloaded) but MySQLdb only supports up to 2.7.
When using select User,Host,Password from mysql.user where User like '%methodjs_postes%'; I get the following error:
SELECT command denied to user 'methodjs'#'localhost' for table 'user'
Just replace localhost with 127.0.0.1
https://chat.stackoverflow.com/rooms/22618/discussion-between-shawn31313-and-suku
As per out chat, the conclusion is :- "Your mysql host is a remote machine and which is not allowing remote mysql connections"