output is like
i displayed result from database in a tabular form using BeautifulTable python. but the result is unorganised.
try:
connection = mysql.connector.connect(host='localhost',
database='testdb',
user='root',
password='Pooja#123')
cur= connection.cursor()
sql = "select ip,ports,services from output where date=now()"
number_of_rows = cur.execute(sql)
table=BeautifulTable()
table.set_style(BeautifulTable.STYLE_DOTTED)
table.column_headers=["ip","ports","services"]
table.column_alignments['ip'] = BeautifulTable.ALIGN_LEFT
table.column_alignments['ports'] = BeautifulTable.ALIGN_LEFT
table.column_alignments['services'] = BeautifulTable.ALIGN_RIGHT
row=cur.fetchall()
for r in row:
table.append_row(r)
print(table)
Related
So currently when I execute SELECT query and retrieve data I have to get results like this:
connection = psycopg2.connect(user="admin",
password="admin",
host="127.0.0.1",
port="5432",
database="postgres_db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM user")
users = cursor.fetchall()
for row in users:
print(row[0])
print(row[1])
print(row[2])
What I want to do is, use column names instead of integers, like this:
for row in users:
print(row["id"])
print(row["first_name"])
print(row["last_name"])
Is this possible, and if it is, then how to do it?
You need to use RealDictCursor, then you can access the results like a dictionary:
import psycopg2
from psycopg2.extras import RealDictCursor
connection = psycopg2.connect(user="...",
password="...",
host="...",
port="...",
database="...",
cursor_factory=RealDictCursor)
cursor = connection.cursor()
cursor.execute("SELECT * FROM user")
users = cursor.fetchall()
print(users)
print(users[0]['user'])
Output:
[RealDictRow([('user', 'dbAdmin')])]
dbAdmin
no need to call fetchall() method, the psycopg2 cursor is an iterable object you can directly do:
cursor.execute("SELECT * FROM user")
for buff in cursor:
row = {}
c = 0
for col in cursor.description:
row.update({str(col[0]): buff[c]})
c += 1
print(row["id"])
print(row["first_name"])
print(row["last_name"])
I'm trying to fetch data from postgreSQL using if statement into QTableWidget, however when I'm applying variable and assigning null value(none), there is nothing showing in my table. And I cannot use where clause with QlineEdit. Is there any possible way to reproduce this code so it works properly?
def LoadData(self):
name = self.Name_search.text()
conn = psycopg2.connect(
database = "postgres",
user = "postgres",
password = "**********",
host = "localhost",
port = "5432"
)
if name is None:
with conn:
cur = conn.cursor()
rows = cur.execute("Select * from swimming_pool_users where name = '%s'",(name))
data = cur.fetchall()
for row in data:
self.AddTable(row)
cur.close()
def AddTable(self,columns):
rowPosition = self.tableWidget2.rowCount()
self.tableWidget2.insertRow(rowPosition)
for i, column in enumerate(columns):
self.tableWidget2.setItem(rowPosition, i, QtWidgets.QTableWidgetItem(str(column)))
def ClearTableData (self):
while (self.tableWidget2.rowCount() > 0):
self.tableWidget2.removeRow(0)
I really don't understand what do you want exactly, but this is an example of how to show data from postgresql database to a QtableWidgit
def exemple_Qtablewidgit(self):
connection = psycopg2.connect(user="postgres",
password="password",
host="localhost",
database="database")
self.cur = connection.cursor()
name = self.lineEdit.text()
self.cur.execute(''' SELECT * FROM exemple WHERE name =%s''', (name,))
data = self.cur.fetchall()
if data :
self.tableWidget.setRowCount(0)
self.tableWidget.insertRow(0)
for row, form in enumerate(data):
for column , item in enumerate(form):
self.tableWidget.setItem(row, column, QTableWidgetItem(str(item)))
column += 1
row_position = self.tableWidget.rowCount()
self.tableWidget_3.insertRow(row_position)
I've got a query that returns the data correctly in MySQL but in Python only returns part of the data.
The query is:
select sc.* from tbl030_shots_chart sc, tbl006_player_team tc where
sc.id_fiba = tc.id_player_feb and
tc.id_team_club = 5
This query in MySQL returns 1030 rows like you can see in this screen cap.
However, If I execute this query with python, I've got only 67 rows. This is my code:
connection = pymysql.connect(host = DDBB.DDBB_FIBA_HOST,
user = DDBB.DDBB_FIBA_USER,
password = DDBB.DDBB_FIBA_PSWD,
db = DDBB.DDBB_FIBA_NAME,
charset = DDBB.DDBB_FIBA_CHARSET,
cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor:
totalRows = cursor.execute("select sc.* from tbl030_shots_chart sc, tbl006_player_team tc where sc.id_fiba = tc.id_player_feb and tc.id_team_club = %s", [5])
print("Total Rows: " + str(totalRows))
And this is the exit:
Why I've got les data from Python than MySQL?
These are the definition of the tables:
tbl030_shots_chart
tbl006_player_team
Edit I:
With inner join doesn't work in python but works in MySQL
However, with python, still returns 76 rows and not 1030 like MySQL.
connection = pymysql.connect(host = DDBB.DDBB_FIBA_HOST,
user = DDBB.DDBB_FIBA_USER,
password = DDBB.DDBB_FIBA_PSWD,
db = DDBB.DDBB_FIBA_NAME,
charset = DDBB.DDBB_FIBA_CHARSET,
cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor:
totalRows = cursor.execute("select sc.* from tbl030_shots_chart as sc inner join tbl006_player_team as pt on sc.id_fiba = pt.id_player_feb and pt.id_team_club = %s", [5])
print("Total Rows: " + str(totalRows))
If I've got the total rows from the cursor with this code:
connection = pymysql.connect(host = DDBB.DDBB_FIBA_HOST,
user = DDBB.DDBB_FIBA_USER,
password = DDBB.DDBB_FIBA_PSWD,
db = DDBB.DDBB_FIBA_NAME,
charset = DDBB.DDBB_FIBA_CHARSET,
cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor:
cursor.execute("select sc.* from tbl030_shots_chart as sc inner join tbl006_player_team as pt on sc.id_fiba = pt.id_player_feb and pt.id_team_club = %s", [5])
totalRows = cursor.rowcount
print("Total Rows: " + str(totalRows))
I've got 76 rows returned and not 1030.
You can try creating a view for this query.
CREATE VIEW your_view AS (
SELECT
t1.id,
t1.id_game,
t1.line,
...
t2.id_team_club,
t2.id_player_feb,
...
FROM tbl030_shots_chart t1
LEFT JOIN
tbl006_player_team t2
)
Then in your python code:
sql = 'SELECT * FROM your_view WHERE id_fiba =id_player_feb AND id_team_club = %s'
with connection.cursor() as cursor:
cursor.execute(sql, (5))
Try to use the cursor rowcount attribute:
with connection.cursor() as cursor:
cursor.execute("select sc.* from tbl030_shots_chart sc, tbl006_player_team tc where sc.id_fiba = tc.id_player_feb and tc.id_team_club = %s", [5])
totalRows=cursor.rowcount
print("Total Rows: " + str(totalRows))
In the .execute method there are no return values defined, so you can get anything.
This is the picture of my data in access:
and below is the code for getting all the data:
def access():
l =[]
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\GOBOTIX\Desktop\Try.mdb;')
cursor = conn.cursor()
cursor.execute('select * from Try')
for row in cursor.fetchall():
l.append(row)
I'm trying to export a python dataframe to a SQL Server table.
Is there a better way to do this? I'm getting errors.
Dataframe - results_out
Output SQL table - FraudCheckOutput
cnn_out = pyodbc.connect('driver={SQL Server};server=XYZ;database=BulkLog;uid=sa;pwd=test')
results_out.to_sql(con=cnn_out, name='FraudCheckOutput', if_exists='replace', flavor='sqlite_master')
Thanks.
Ok, this supposed to make the work done:
import pypyodbc
def database_insert(query, params=())
conn_params = 'driver={SQL Server};server=XYZ;database=BulkLog;uid=sa;pwd=test'
try:
conn = pypyodbc.connect(conn_params)
except pypyodbc.Error, e:
print str(e)
else:
if conn.connected:
db = conn.cursor()
db.execute(query, params).commit()
finally:
if conn:
conn.close()
SQL_INSERT_QUERY = """
INSERT INTO table_name (
[field_name1],
[field_name2]
)
VALUES (
1,
'vale string'
)
WHERE
field_name3 = ?
"""
database_insert(SQL_INSERT_QUERY, ('field_name3_value',))
in pyodbc usage is very similar
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()
cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')")
cnxn.commit()
more on http://code.google.com/p/pyodbc/wiki/GettingStarted