I am following this tutorial to connect to a PostgreSQL database stored on my computer.
I am using Windows 10 and I have installed PostgreSQL 9.3
I run the following code:
import psycopg2
class PostgreSQL():
def __init__(self):
self.conecta()
def conecta(self):
#establishing the connection
conn = psycopg2.connect(
database="PokerTracker 4 Database", user='postgres', password='dbpass', host='localhost', port= '5432')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Executing an MYSQL function using the execute() method
cursor.execute("select version()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ",data)
conn.close()
if __name__=='__main__':
PostgreSQL()
I receive the following error from the cmd while running the script:
C:\Users\USUARIO\Desktop\OMAHA>python postgresql.py
Traceback (most recent call last):
File "C:\Users\USUARIO\Desktop\OMAHA\postgresql.py", line 18, in <module>
PostgreSQL()
File "C:\Users\USUARIO\Desktop\OMAHA\postgresql.py", line 4, in __init__
self.conecta()
File "C:\Users\USUARIO\Desktop\OMAHA\postgresql.py", line 7, in conecta
conn = psycopg2.connect(
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\psycopg2\__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError
What am I doing wrong? I copied the code from the tutorial.
If someone is trying to connect to Pokertracker database, the error was the database name was uncorrect. Go on pokertracker to File->Open User Data Folder. Open config folder, open pokertracker.cfg and there you have all the info.
In my case this are the parameters:
import psycopg2
class PostgreSQL():
def __init__(self):
self.conecta()
def conecta(self):
hostname = 'localhost'
username = 'postgres'
password = 'dbpass'
database = 'PT4DB'
myConnection = psycopg2.connect( host=hostname, user=username, password=password, dbname=database )
cursor = myConnection.cursor()
cursor.execute("""SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'""")
for table in cursor.fetchall():
print(table)
myConnection.close()
if __name__=='__main__':
PostgreSQL()
There you have the notes table. You can't edit the notes, they are protected by the system of Pokertracker. cheers
Related
My Python code shown below is written to create a SQL Server connection using Windows authentication. I have constraints to use adodbapi library for database connectivity.
Please can anyone tell me what is missing from this code? I referred to the library's documentation, but there is nothing mentioning Windows authentication.
I referred to a lot of articles about that exception. But they seems there's no help to understand the nature of exception and its resolution.
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.
Code:
import configparser
import adodbapi
config = configparser.ConfigParser()
config.read("C:/plugin/configsql.ini")
_SERVER_NAME = config['SQL']['SERVER_NAME']
_DATABASE = config['SQL']['DATABASE']
conn = adodbapi.connect("PROVIDER=MSOLEDBSQL;Data Source={0};Database={1};Integrated Security = True;".format(_SERVER_NAME,_DATABASE))
print(conn)
Exception:
Traceback (most recent call last):
File "C:\Arelle-master\venv1\lib\site-packages\adodbapi\adodbapi.py", line 113, in connect
co.connect(kwargs)
File "C:\Arelle-master\venv1\lib\site-packages\adodbapi\adodbapi.py", line 275, in connect
self.connector.Open() # Open the ADO connection
File "", line 3, in Open
File "C:\Arelle-master\venv1\lib\site-packages\win32com\client\dynamic.py", line 287, in ApplyTypes
result = self.oleobj.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Provider', 'Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.', None, 1240640, -2147217887), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "winAuthentication.py", line 8, in
conn = adodbapi.connect("PROVIDER=MSOLEDBSQL;Data Source={0};Database={1};Integrated Security = True;".format(_SERVER_NAME,_DATABASE))
File "C:\Arelle-master\venv1\lib\site-packages\adodbapi\adodbapi.py", line 117, in connect
raise api.OperationalError(e, message)
adodbapi.apibase.OperationalError: (com_error(-2147352567, 'Exception occurred.', (0, 'Provider', 'Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.', None, 1240640, -2147217887), None), 'Error opening connection to "PROVIDER=MSOLEDBSQL;Data Source=MSSQLSERVER01;Database=TESTDB;Integrated Security = True;"')
Have you tried Trusted_Connection=yes? Here is my connection string that uses windows authentication (using pyodbc) but should be the same connection parameter, not Integrated Security.
conn = pyodbc.connect('Driver={SQL Server};'
'Server=ServerName;'
'Database=DatabaseName;'
'Trusted_Connection=yes;')
Or perhaps Integrated Security = SSPI, found mentioned here http://adodbapi.sourceforge.net/quick_reference.pdf
'Integrated Security=SSPI'
I have a SQL Server on which I have databases that I want to use pandas to alter that data. I know how to get the data using pyodbc into a DataFrame, but then I have no clue how to get that DataFrame back into my SQL Server.
I have tried to create an engine with sqlalchemy and use the to_sql command, but I can not get that to work because my engine is never able to connect correctly to my database.
import pyodbc
import pandas
server = "server"
db = "db"
conn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+db+';Trusted_Connection=yes')
cursor = conn.cursor()
df = cursor.fetchall()
data = pandas.DataFrame(df)
conn.commit()
You can use pandas.DataFrame.to_sql to insert your dataframe into SQL server. Databases supported by SQLAlchemy are supported by this method.
Here is a example how you can achieve this:
from sqlalchemy import create_engine, event
from urllib.parse import quote_plus
import logging
import sys
import numpy as np
from datetime import datetime, timedelta
# setup logging
logging.basicConfig(stream=sys.stdout,
filemode='a',
format='%(asctime)s.%(msecs)3d %(levelname)s:%(name)s: %(message)s',
datefmt='%m-%d-%Y %H:%M:%S',
level=logging.DEBUG)
logger = logging.getLogger(__name__) # get the name of the module
def write_to_db(df, database_name, table_name):
"""
Creates a sqlalchemy engine and write the dataframe to database
"""
# replacing infinity by nan
df = df.replace([np.inf, -np.inf], np.nan)
user_name = 'USERNAME'
pwd = 'PASSWORD'
db_addr = '10.00.000.10'
chunk_size = 40
conn = "DRIVER={SQL Server};SERVER="+db_addr+";DATABASE="+database_name+";UID="+user_name+";PWD="+pwd+""
quoted = quote_plus(conn)
new_con = 'mssql+pyodbc:///?odbc_connect={}'.format(quoted)
# create sqlalchemy engine
engine = create_engine(new_con)
# Write to DB
logger.info("Writing to database ...")
st = datetime.now() # start time
# WARNING!! -- overwrites the table using if_exists='replace'
df.to_sql(table_name, engine, if_exists='replace', index=False, chunksize=chunk_size)
logger.info("Database updated...")
logger.info("Data written to '{}' databsae into '{}' table ...".format(database_name, table_name))
logger.info("Time taken to write to DB: {}".format((datetime.now()-st).total_seconds()))
Calling this method should write your dataframe to the database, note that it will replace the table if there is already a table in the database with the same name.
I am trying to connect to local MS SQL Express Edition. I am using canopy for Python editing.
Code:
import pymssql
conn = pymssql.connect(server='******\SQLEXPRESS',user = 'MEA\*****',password='*****',database='BSEG')
cursor = conn.cursor()
cursor.execute('SELECT * FROM Table')
print(cursor.fetchone())
conn.close()
Error::
pymssql.pyx in pymssql.connect (pymssql.c:10734)()
_mssql.pyx in _mssql.connect (_mssql.c:21821)()
_mssql.pyx in _mssql.MSSQLConnection.init (_mssql.c:5917)()
ValueError: too many values to unpack (expected 2)
user = 'MEA\*****',password='*****'
MEA\***** seems to be Windows login, in this case you shouldn't pass in any password, your user name is enough, but you also should use Integrated security or Trusted parameter in your connection string
It should be smth like this:
server='******\SQLEXPRESS',Trusted_Connection=yes,database='BSEG'
I'd like to connect from IPython notebook to a SQL-Server database via integrated security.
Is this possible? I'm guessing yes it is.
How do I format the connection string in the following?
import pandas as pd
import pandas.io.sql as psql
sql = "SELECT * FROM WHdb.dbo.vw_smallTable"
cnx = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=WHdb;Data Source=OurServerName"
data = psql.read_sql(sql, cnx)
This just gives an error.
Am I going about the cnx incorrectly?
You need to install the package, pypyodbc
!pip install pypyodbc
Then, you can import it as follows:
import pypyodbc as podbc
You can now create the connection:
conn = podbc.connect("Driver={SQL Server};Server=<YourServer>;Database=<YourDatabase>;uid=<YourUserName>;pwd=<YourPassword>"
Finally, you fetch your data as follows:
cursor = conn.cursor()
sql = "SELECT * FROM WHdb.dbo.vw_smallTable"
cursor.execute(sql)
data = cursor.fetchone()
while data:
print(str(data[0]) + ", " + ... + ", " + str(data[n-1]))
data = cursor.fetchone()
conn.close()
Note that n = number of columns in your table.
This is what worked for me well...
import pyodbc
server = 'myserver'
database = 'mydb'
username = 'myusername'
password = 'mypassword'
#Connection String
connection = pyodbc.connect('DRIVER={SQL Server Native Client 11.0};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = connection.cursor()
#Sample select query
cursor.execute("SELECT ##version;")
row = cursor.fetchone()
while row:
print row[0]
row = cursor.fetchone()
Can we access SQL Server data from Iron Python script file if so how I m trying this following code ?
import sys
import clr
clr.AddReference("System.Windows")
from System.Windows import Application
import pypyodbc
constr="DRIVER={SQL Server Native Client 10.0};Data Source=SERVERName;Initial Catalog=DBName;Integrated Security=True"
cnxn=pypyodbc.connect(constr)
da=cnxn.cursor("Select Ename from tbl_Empployee where Emp_id=1",cn)
da.execute();
for row in da.fetchall():
for field in row:
Application.Current.RootVisual.FindName("textBox2").Text = field
You can use the .net native types, see: What's the simplest way to access mssql with python or ironpython?
your code could look like this:
import clr
clr.AddReference('System.Data')
from System.Data.SqlClient import SqlConnection, SqlParameter
conn_string = 'data source=SRG3SERVER; initial catalog=vijaykumarDB; trusted_connection=True'
connection = SqlConnection(conn_string)
connection.Open()
command = connection.CreateCommand()
command.CommandText = 'Select Ename from tbl_Empployee where Emp_id=#employeeId'
command.Parameters.Add(SqlParameter('#employeeId', 1))
reader = command.ExecuteReader()
while reader.Read():
print reader['Ename']
connection.Close()