how to connect studio3t to pymongo on localhost - linux

I'm creating a collection and using localhost but studio 3t doesn't show any tree
I clicked connect tab on studio 3t and made a new connection on it's default (localhost) but when i connect to this new connection the collection that I have created isn't showing on studio 3t
>>> import pymongo
>>> from pymongo import MongoClient
>>> myClient = MongoClient('localhost',username='myusername',password='mypassword')
>>> db = myClient.mydb
>>> users = db.users
>>> user1 = {"username": "nick", "password": "mysecurepass","fav_num": 445, "hobbies": ["python", "games","pizza"]}
>>> user_id = users.insert_one(user1).inserted_id

Related

Can't connect to MySQL from Jupyter Lab using ipython-sql

I'm running MySQL in a Docker container, and in my jupyter lab I have the following cell:
# Importing module
import mysql.connector
# Creating connection object
mydb = mysql.connector.connect(
host = "localhost",
port = 3307,
user = "bob",
password = "1234",
database = 'testDB'
)
# Printing the connection object
print(mydb)
Which prints: <mysql.connector.connection_cext.CMySQLConnection object at 0x7fc633769dd0>
But I want to connect using ipython-sql, so I load the extension with %load_ext sql, but when I try:
%sql mysql://bob:1234#localhost:3307/testDB
I get the error:
Connection info needed in SQLAlchemy format, example:
postgresql://username:password#hostname/dbname
or an existing connection: dict_keys([])
No module named 'MySQLdb'
Connection info needed in SQLAlchemy format, example:
postgresql://username:password#hostname/dbname
or an existing connection: dict_keys([])

How connect to Local Postgresql server and create database from Python Desktop App

How connect to Local Postgresql server and create database from Python Desktop App
my code :
import psycopg2
conn_string = "host='localhost' dbname='database' user='root' password='root'"
conn = psycopg2.connect(conn_string)
print("Database opened successfully")
conn.close()
print("Database Closed successfully")
You can put these lines after you connect to DB (after line no 4).
cursor = conn.cursor();
cursor.execute("create database my_new_database");
Full code will look like
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
conn_string = "host='localhost' dbname='postgres' user='root' password='root'"
conn = psycopg2.connect(conn_string)
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT);
print("Database opened successfully")
cursor = conn.cursor();
cursor.execute("create database my_new_database");
conn.close()
conn_string = "host='localhost' dbname='my_new_database' user='root' password='root'"
conn = psycopg2.connect(conn_string)
# here you need to populate database wit tables "create table mytbl..."
conn.close()
print("Database Closed successfully")

Get latest Document with respect to (time or Id) using Pymongo only

In MongoDB, this technique is commonly used to obtain the latest document with respect to (time or ID):
db.collection.find().sort({ "_id": -1 }).limit(1);
MySchema.find().sort({ _id: -1 }).limit(1)
db.getLastInsertedDocument.find({}).sort({_id:-1}).limit(1);
But when I use pymongo to find the latest entry in my collection the code below gives an error.
from pymongo import MongoClient
import random
import datetime
import time
import pprint
from datetime import datetime
#from bson import ObjectId
client = MongoClient()
client = MongoClient('localhost', 27017)
db = client.sensor_temperature # createdb
posts = db.posts2
print('Total Record for the collection: ' + str(posts.count()))
x=datetime.now().strftime("%H:%M:%S")
record=posts.find().sort({ "_id": -1 }).limit(1) ### ERR
#record=posts.find({"start_date":new Date()}).pretty() #### ERR
#record=posts.findOne({"_id": x}) #### <pymongo.cursor.Cursor object at 0x0141FCD0>
pprint.pprint(record)
text=record
print(text)
How to get the latest records using Pymongo only?
Some of the pymongo driver commands don't match exactly to the mongodb shell. The documentation explains the method calls. This should work:
from pymongo import MongoClient, DESCENDING
<...>
record=posts.find().sort('_id', DESCENDING).limit(1)
pprint.pprint(list(record)[0])

Connect to AWS RDS Postgres database with python

I have an existing postgres table in RDS with a database name my-rds-table-name
I've connected to it using pgAdmin4 with the following configs of a read-only user:
host_name = "my-rds-table-name.123456.us-east-1.rds.amazonaws.com"
user_name = "my_user_name"
password = "abc123def345"
I have verified that I can query against the table.
However, I cannot connect to it using python:
SQLAlchemy==1.2.16
psycopg2-binary==2.7.6.1
mysqlclient==1.4.1
With:
import psycopg2
engine = psycopg2.connect(
database="my-rds-table-name",
user="my_user_name",
password="abc123def345",
host="my-rds-table-name.123456.us-east-1.rds.amazonaws.com",
port='5432'
)
It fails with
psycopg2.OperationalError: FATAL: database "my-rds-table-name" does not exist
Similarly, if I try to connect to it with sqlalchemy:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: database "my-rds-table-name" does not exist
What am I missing?
Thank's John Rotenstein for your comment.
As he pointed out, my-rds-table-name is the database instance name, not the database name, the default database name is postgres.
import psycopg2
engine = psycopg2.connect(
database="postgres",
user="my_user_name",
password="abc123def345",
host="my-rds-table-name.123456.us-east-1.rds.amazonaws.com",
port='5432'
)
Using sqlalchemy you can do the following:
engine = create_engine('postgresql://postgres:postgres#<AWS_RDS_end-point>:5432/postgres')
Then you can update your database.
For example:
df = pd.DataFrame({'A': [1,2], 'B':[3,4]})
df.to_sql('tablename', engine, schema='public', if_exists='append', index=False)

cx_Oracle & Connecting to Oracle DB Remotely

How do you connect to a remote server via IP address in the manner that TOAD, SqlDeveloper, are able to connect to databases with just the ip address, username, SID and password?
Whenever I try to specify and IP address, it seems to be taking it locally.
In other words, how should the string for cx_Oracle.connect() be formatted to a non local database?
There was a previous post which listed as an answer connecting to Oracle via cx_Oracle module with the following code:
#!/usr/bin/python
import cx_Oracle
connstr='scott/tiger'
conn = cx_Oracle.connect(connstr)
curs = conn.cursor()
curs.execute('select * from emp')
print curs.description
for row in curs:
print row
conn.close()
I like to do it this way:
ip = '192.168.0.1'
port = 1521
SID = 'YOURSIDHERE'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)
db = cx_Oracle.connect('username', 'password', dsn_tns)
One of the main reasons I like this method is that I usually have a TNSNAMES.ORA file lying around someplace, and I can check that the dsn_tns object will do the right thing by doing:
print dsn_tns
and comparing the output to my TNSNAMES.ORA
You can specify the server in the connection string, e.g.:
import cx_Oracle
connstr = 'scott/tiger#server:1521/orcl'
conn = cx_Oracle.connect(connstr)
"server" is the server, or the IP address if you want.
"1521" is the port that the database is listening on.
"orcl" is the name of the instance (or database service).
import cx_Oracle
CONN_INFO = {
'host': 'xxx.xx.xxx.x',
'port': 12345,
'user': 'user_name',
'psw': 'your_password',
'service': 'abc.xyz.com',
}
CONN_STR = '{user}/{psw}#{host}:{port}/{service}'.format(**CONN_INFO)
connection = cx_Oracle.connect(CONN_STR)
Instead of specifying the SID, you can create a dsn and connect via service_name like:
import cx_Oracle
ip = '192.168.0.1'
port = 1521
service_name = 'my_service'
dsn = cx_Oracle.makedsn(ip, port, service_name=service_name)
db = cx_Oracle.connect('user', 'password', dsn)
The benefit of using the service name instead of the specific instance identifier (SID), is that it will work in a RAC environment as well (using a SID won't). This parameter is available as of cx_Oracle version 5.1.1 (Aug 28, 2011)
import cx_Oracle
dsn = cx_Oracle.makedsn(host='127.0.0.1', port=1521, sid='your_sid')
conn = cx_Oracle.connect(user='your_username', password='your_password', dsn=dsn)
conn.close()
import cx_Oracle
ip = '172.30.1.234'
port = 1524
SID = 'dev3'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)
conn = cx_Oracle.connect('dbmylike', 'pass', dsn_tns)
print conn.version
conn.close()

Resources