How connect to database and get data via python like in R - python

I new in python. I need connect to mysql database and get data. Before that, I easily took data via R using rodbslike this.
library(DBI)
library(RMySQL)
db_user = 'k'
db_password = 'F6'
db_name = 'meg'
db_table = 'dat'
db_host = 'my.g2s' # for local access
db_port = 3306
# 3. Read data from db
mydbV7 = dbConnect(MySQL(), user = db_user, password = db_password,
dbname = db_name, host = db_host, port = db_port)
sV7 = paste0("select * from ", db_table)
rsV7 = dbSendQuery(mydbV7, sV7)
df = fetch(rsV7, n = -1)
but when i tried to implement the same principle in python i get errors
import pyodbc
>>> db_user = 'k'
>>> db_password = 'F6'
>>> db_name = 'meg'
>>> db_table = 'dat'
>>> db_host = 'my.g2s' # for local access
>>> db_port = 3306
>>> mydbV7 = dbConnect(MySQL(), user = db_user, password = db_password,
... dbname = db_name, host = db_host, port = db_port)
File "<stdin>", line 2
... dbname = db_name, host = db_host, port = db_port)
^
SyntaxError: positional argument follows keyword argument
How can i correct get data via python 3.9?
As always, I appreciate any of your help.

As describe in the MySQL documentation, you can import mysql.connector and then use :
cnx = mysql.connector.connect(user = 'scott',
password = 'password',
host = '127.0.0.1',
database = 'employees')
Of course, you have to change the values with yours.
cnx will then represent the connection with your database.

Related

Python - Postgres - psycopg2 - ThreadedConnectionPool - Connect to primary in HA cluster

Does the Python/psycopg2/ThreadedConnectionPool accept a parameter that tells it to only connect to the primary server in an Postgres HA cluster? The equivalent jdbc connection string would look something like, note the targetServerType=primary:
jdbc:postgresql://serverName1:5432,serverName2:5432,serverName3:5432/dataBaseName?loadBalanceHosts=false&targetServerType=primary
How can I pass the targetServerType to the ThreadedConnectionPool in the connection setup below:
self._pg_pool = psycopg2.pool.ThreadedConnectionPool(
minconn = 1,
maxconn = 2,
host = 'serverName1, serverName2, serverName3',
database = 'dataBaseName1',
user = 'userName',
password = 'passWord',
port = "5432",
application_name = 'MyTestApp'
)

TypeError: sqlrunner.run_query() missing 1 required positional argument: 'sql_string'

Iam getting in error while error executing I coulf not find out the issue can anyone help me with this
TypeError: sqlrunner.run_query() missing 1 required positional argument: 'sql_string'
'''
import psycopg2
class sqlrunner():
hostname = 'localhost'
database = 'postgres'
username = 'postgres'
pwd = 'Naveen$1234'
port_id = 5432
table_name = 'my_table'
def connect(self):
self.connect = psycopg2.connect( host = self.hostname,
user = self.username,
password = self.pwd,
dbname = self.database,
port= self.port_id )
self.cursor=self.connect.cursor()
def run_query(self,sql_string):
cursor=self.cursor
sql_string = "drop table if EXISTS my_table"
print(sql_string)
cursor.execute(sql_string)
if __name__ == '__main__':
db=sqlrunner()
db.connect()
db.run_query()
'''
You have the query string in the method.
Two options:
Pass the query string as variable to the method and remove it from the method:
...
db.run_query("drop table if EXISTS my_table")
Or don't add a parameter to the signature of the method:
...
def run_query(self):
...

Not able to iterate mongo object in python

I am trying to get the records (books), which are present the in Mongo DB collection "books". I am using pymongo and flask.
Below is my code. In the code, if I remove the query update line (query.update({'author': 'sachin'})), it works fine.
What is the problem while updating the query dict?
from pymongo import connection as pymongo_client
import urllib
def get_books(query, skip_val=0, limit=None):
conn, client = _connect()
if limit:
result = client.books.find(query).skip(skip_val).limit(limit)
else:
result = client.books.find(query)
conn.close()
return result
def _connect():
user = "root"
password = "password"
host = "172.17.1.14"
port = "27017"
db_name = "books"
auth_database = "admin"
if user and password and auth_database:
uri = "mongodb://%s:%s#%s:%s/%s" % (
user, urllib.quote_plus(password), host, port, auth_database)
else:
uri = "mongodb://%s:%s" % (host, port)
conn = pymongo_client.Connection(uri, j=True)
db = conn[db_name]
return conn, db
query = {'project_name': 'cricket'}
books = get_books(query)
query.update({'author': 'sachin'})
for book in books:
print book

Python re-connecting to MySQLdb

I have the following:
class DBConnection:
def __init__(self, DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME):
self.host = DB_HOST
self.port = DB_PORT
self.name = DB_NAME
self.user = DB_USER
self.password = DB_PASSWORD
self.conn = None
self.cursor = None
def get_conn(self):
if self.conn is None:
self.conn = MySQLdb.connect (host = self.host, port = self.port, db = self.name, user = self.user, passwd = self.password)
return self.conn
def close_conn(self):
if self.conn:
self.conn.close()
return self.conn
This is what it looks like when I try and reconnect:
>>> from db_conn import DBConnection
>>> db = DBConnection(DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME)
>>> db.get_conn()
<_mysql.connection open to '127.0.0.1' at 7fbb1b8a2420>
>>> db.close_conn()
>>> db.conn
<_mysql.connection closed at 7fbb1b8a2420>
>>> db.get_conn()
<_mysql.connection closed at 7fbb1b8a2420>
Why won't it allow me to re-open the connection? How would I re-open it, or do I need to create a new instance?
You're testing whether self.conn is 'None' but it's not - it's still a mysql connection object. One of its properties or methods will tell you whether it's open or not, so you could test that instead, or set self.conn to None in close_conn if that's easier.
The function "close_conn" return self_conn after it colseed connection. So the virable self_conn always be true, right?

Writing an object-oriented MySQLdb connection

I am trying to learn OOP, and I am using the database connection via MySQLdb as my first test. This is what I have so far:
class DBConnection:
def __init__(self, DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME):
self.host = DB_HOST
self.port = DB_PORT
self.name = DB_NAME
self.user = DB_USER
self.password = DB_PASSWORD
def get_conn(self):
conn = MySQLdb.connect (host = self.DB_HOST, port = self.DB_PORT,
db = DB_NAME, user = DB_USER,
passwd = DB_PASSWORD)
return conn
def get_cursor(self):
cursor = self.conn.cursor()
return cursor
def get_dict_cursor(self):
dict_cursor = self.conn.cursor(MySQLdb.cursors.DictCursor)
return dict_cursor
Is the above valid? Does self.conn refer to get_conn() or is this an invalid reference. How would I establish a connection to the database and then get a cursor, using the python shell?
You haven't defined self.conn anywhere. You're only setting conn as a local inside of get_conn. Define self.conn in your constructor, and then update get_conn to set self.conn. Like this:
class DBConnection:
def __init__(self, DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME):
self.host = DB_HOST
self.port = DB_PORT
self.name = DB_NAME
self.user = DB_USER
self.password = DB_PASSWORD
self.conn = None
def get_conn(self):
self.conn = MySQLdb.connect(host = self.host,
port = self.port,
db = self.name,
user = self.user,
passwd = self.password)
Also, check whether self.conn is set first as opposed to creating a new one each time in get_conn, like this:
def get_conn(self):
if self.conn is None:
self.conn = MySQLdb.connect(host = self.host,
port = self.port,
db = self.name,
user = self.user,
passwd = self.password)
return self.conn
Finally, call the get_conn method like this:
mydbconnobj = DBConnection('localhost',3306,'foouser','foopass','foodbname')
mydbconn = mydbconnobj.get_conn()

Categories