Python 3.4 with psycopg2
I used this guide to set up a basic psycopg2 connection like so:
#!/usr/bin/python
import psycopg2
import sys
import pprint
def main():
conn_string = "dbname='CIBTST' host='XX.XX.XXX.XX' port='XXXX' user='XXXXX' password='XXXX'"
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.execute("My_select")
records = cursor.fetchall()
pprint.pprint(records)
if __name__ == "__main__":
main()
I get this traceback:
Traceback (most recent call last):
File "C:\Users\pi24926\Desktop\Python\doSMS.py", line 14, in <module>
main()
File "C:\Users\pi24926\Desktop\Python\doSMS.py", line 8, in main
conn = psycopg2.connect(conn_string)
File "C:\Python34\lib\site-packages\psycopg2\__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
psycopg2.OperationalError
When I try the same select statement in another client (Toad) it seems to operate correctly. Any suggestions will be great. Thank you!
EDIT: The source of problem is: PORT. If I run:
#!/usr/bin/python
import psycopg2
import sys
import pprint
def main():
conn_string = "dbname='CIBTST' host='XX.XX.XXX.XX' user='XXXXX' password='XXXX'"
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.execute("My_select")
records = cursor.fetchall()
pprint.pprint(records)
if __name__ == "__main__":
main()
Then I get:
Traceback (most recent call last):
File "C:\Users\pi24926\Desktop\Python\doSMS.py", line 14, in <module>
main()
File "C:\Users\pi24926\Desktop\Python\doSMS.py", line 8, in main
conn = psycopg2.connect(conn_string)
File "C:\Python34\lib\site-packages\psycopg2\__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not connect to server: Connection timed out (0x0000274C/10060)
Is the server running on host "XXXXXXX" and accepting
TCP/IP connections on port 5432?
I can only connect under port 1522 for some reason. Any ideas?
The problem was with database...
It is an Oracle, so i should use cx_Oracle instead of psycopg2.
Related
struggling for a week already with my issue, hope you'll be able to explain to me what is wrong here.
I'm trying to connect Clickhouse DB I have on the remote server, which is on the absolutely default settings. So I'm connecting to a remote server and creating a tunnel on my machine.
import sshtunnel as sshtunnel
from clickhouse_driver import connect
server = sshtunnel.SSHTunnelForwarder(
('host', 22),
ssh_username='username',
ssh_pkey="username.openssh",
ssh_private_key_password="password",
remote_bind_address=('localhost', 8123),
local_bind_address=('localhost', 555)
)
server.start()
conn = connect(host='localhost', port=555, database='ertb')
cursor = conn.cursor()
cursor.execute('SHOW TABLES')
cursor.fetchall()
server.stop()
and I receive this error
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/alerts/ssh_coonection.py", line 42, in <module>
cursor.execute('SHOW TABLES')
File "C:\Users\user\PycharmProjects\alerts\venv\lib\site-packages\clickhouse_driver\dbapi\cursor.py", line 102, in execute
**execute_kwargs
File "C:\Users\user\PycharmProjects\alerts\venv\lib\site-packages\clickhouse_driver\client.py", line 205, in execute
self.connection.force_connect()
File "C:\Users\user\PycharmProjects\alerts\venv\lib\site-packages\clickhouse_driver\connection.py", line 180, in force_connect
self.connect()
File "C:\Users\user\PycharmProjects\alerts\venv\lib\site-packages\clickhouse_driver\connection.py", line 256, in connect
return self._init_connection(host, port)
File "C:\Users\user\PycharmProjects\alerts\venv\lib\site-packages\clickhouse_driver\connection.py", line 237, in _init_connection
self.send_hello()
File "C:\Users\user\PycharmProjects\alerts\venv\lib\site-packages\clickhouse_driver\connection.py", line 325, in send_hello
write_binary_str(self.user, self.fout)
File "C:\Users\user\PycharmProjects\alerts\venv\lib\site-packages\clickhouse_driver\writer.py", line 19, in write_binary_str
text = text.encode('utf-8')
AttributeError: 'NoneType' object has no attribute 'encode'
I really tried to understand from where this NoneType object appears, but a bit stuck in code.
There are two issues:
is not passed user and password that leads to the error 'NoneType' object has no attribute 'encode'
used the wrong port to access to CH (clickhouse-driver is designed to communicate with ClickHouse server over native protocol (TCP) that by default use port 9000 for non-secure communication (see Issue connecting to Dockerized Clickhouse Server with Python driver for details))
import sshtunnel as sshtunnel
from clickhouse_driver import connect
with sshtunnel.SSHTunnelForwarder(
('localhost', 22),
ssh_username="root",
ssh_password="root",
remote_bind_address=('localhost', 9000)) as server:
local_port = server.local_bind_port
print(local_port)
conn = connect(f'clickhouse://default:#localhost:{local_port}/ertb')
#conn = connect(host='localhost', port=local_port, database='ertb', user='default', password='')
cursor = conn.cursor()
cursor.execute('SHOW TABLES')
print(cursor.fetchall())
We are trying to access the database of Odoo running on 104.154.90.232 through Python. I have used psycopg2 to connect.
My code is like this:
import psycopg2
import sys
import pprint
conn_string = "host='104.154.90.232' dbname='dbname' user='user' password='password'"
print "connecting to the database\n ->%s"%(conn_string)
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.execute("SELECT * FROM hr_employee")
records = cursor.fetchall()
pprint.pprint(records)
The error is:
Traceback (most recent call last):
File "test.py", line 6, in <module>
conn = psycopg2.connect(conn_string)
File "C:\Python27\lib\site-packages\psycopg2\__init__.py", line 130, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not connect to server: Connection timed out (0x0000274C/10060)
Is the server running on host "104.154.90.232" and accepting TCP/IP connections on port 5432?
Can someone help me establish the connection?
As far as i know, the default pg_hba.conf file only allows connections resp. authentification from the local system. You have to define new rules for external access. It's described in the file, how to do that.
Then ofcourse there has to be a correctly configured database user for odoo.
Here is code :
#!/usr/bin/env python
import pyhs2
try:
with pyhs2.connect(host='localhost',
port=10001,
authMechanism="PLAIN",
user='root',
password='test',
database='test') as conn:
with conn.cursor() as cur:
#Show databases
print cur.getDatabases()
#Execute query
cur.execute("select * from raw_stats")
#Return column info from query
print cur.getSchema()
#Fetch table results
for i in cur.fetch():
print i
except Thrift.TException, tx:
print '%s' % (tx.message)
Error!
Traceback (most recent call last): File "/usr/local/py/test.py", line
8, in database='default') as conn: File
"/usr/lib/python2.6/site-packages/pyhs2/init.py", line 7, in
connect
return Connection(*args, **kwargs) File "/usr/lib/python2.6/site-packages/pyhs2/connections.py", line 46, in
init
transport.open() File "/usr/lib/python2.6/site-packages/pyhs2/cloudera/thrift_sasl.py", line
55, in open
self._trans.open() File "/usr/lib64/python2.6/site-packages/thrift/transport/TSocket.py", line
101, in open
message=message) thrift.transport.TTransport.TTransportException: Could not connect to localhost:10001
It resolved by starting hiveServer2 service and changing the port 10000.
I am newbie to python,I have simple code to connect database using MySQLdb and Python3.4 running in localhost.
Python Code:
#!c:/Python34/python.exe -u
import cgitb ,cgi
import sys
import MySQLdb
conn = MySQLdb.connect(host='localhost',port=3306,
db='example2',
user='root',
password='tiger')
cursor = conn.cursor()
if conn:
print("sucess")
But getting error ,while executing a code
Error:
Traceback (most recent call last):
File "<pyshell#27>", line 4, in <module>
password='tiger')
File "C:\Python34\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "C:\Python34\lib\site-packages\MySQLdb\connections.py", line 204, in __init__
super(Connection, self).__init__(*args, **kwargs2)
TypeError: an integer is required (got type str)
Please give some suggestion
You need to remove the single quotes from the port.
conn = MySQLdb.connect(host='localhost',
port=3306,
database='example2',
user='root',
password='tiger')
I have been trying to create a database in python using the MySQL module. Here's the code:
import MySQLdb
conn = MySQLdb.connect(host = '127.0.0.1', user='root', passwd='', db='test', port='3306')
cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
row = cursor.fetchone()
print "server version:",row[0]
cursor.close()
conn.close()
I had errors in initial steps relating to the host name, which I changed from localhost to the local IP and added a port keyword which seems to work with the quotes only. Apart from this, I am encountering the following error:
Traceback (most recent call last):
File "C:\Python27\server_version", line 4, in <module>
conn = MySQLdb.connect(host = '127.0.0.1', user='root', passwd='', db='bhavin', port='3306')
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)
TypeError: an integer is required
port should be an integer, not a string:
conn = MySQLdb.connect(host='127.0.0.1',
user='root',
passwd='',
db='test',
port=3306)
Though, note that 3306 is a default port used if not provided explicitly:
port
TCP port of MySQL server. Default: standard port (3306).
Any way you are not creating a db table with that code, you are going to get an error, like "No such table exists" or something like that. Your should try: CREATE TABLE IF NOT EXISTS(" // columns of your table with the type like integer or varchar