Skip to content

Instantly share code, notes, and snippets.

@JorgeFrancoIbanez
Last active June 13, 2019 14:55
Show Gist options
  • Save JorgeFrancoIbanez/f6ddf1f0a756d0615d05867ef78ee222 to your computer and use it in GitHub Desktop.
Save JorgeFrancoIbanez/f6ddf1f0a756d0615d05867ef78ee222 to your computer and use it in GitHub Desktop.
Python connections to databases
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
cluster = Cluster(['<HOST>'], auth_provider=PlainTextAuthProvider(username='<USERNAME>',password='<PASSWORD>'), protocol_version=2)
session = cluster.connect()
print('ConnectING to a valide keyspace')
row = session.execute('use <KEYSPACE>')
print(row)
print('Available keyspace')
row = session.execute('select * from system.schema_keyspaces')
for i in row:
print(i)
Python connections to databases
import sys
from couchbase.cluster import Cluster, PasswordAuthenticator
cluster = Cluster('couchbase://<HOST>:<PORT>')
print("connecting")
cluster.authenticate(PasswordAuthenticator('<USERNAME>','<PASSWORD>'))
cb = cluster.open_bucket('<BUCKET>')
from pymongo import MongoClient
#CONNECT AS USER WITH ADMIN PRIVILEGES
client = MongoClient('mongodb://<USERNAME>:<PASSWORD>@<HOST>/<DABTASE_NAME>?authSource=admin')
db = client.get_database()
print(db.collection)
import mysql.connector
mydb = mysql.connector.connect(
host='<HOST>',
user='<USERNAME>',
password='<PASSWORD>',
database='<DATABASE_NAME>')
mycursor=mydb.cursor()
print(mycursor.execute("show databases;"))
import psycopg2 as psy
try:
string="host='<HOST>' dbname='<DATABASE_NAME>' user='<USERNAME>' password='<PASSWORD>'"
print("connecting")
connection= psy.connect(string)
print("connected")
cursor = connection.cursor()
cursor.execute("select version();")
record = cursor.fetchone()
print(record)
cursor.close()
connection.close()
except:
print("error")
import redis
try:
conn= redis.StrictRedis(
host='<HOST>',
port='<PORT>',
password=None #you can set a password to access the database. If not by default leave None as value
)
print conn
conn.ping()
print('Connected')
except Exception as ex:
print('Error', ex)
exit('Connection Failed.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment