I have a data which looks like (as example) -
{"phone_number": "XXX1","phone_number_country": "XXX2","text": "XXX2"}
where XXX is my data (it can be different types of data)
Also, I have DB with data, which looks like (as example) -
[
Data is taken from DB:
con = sqlite3.connect('dab')
cur = con.cursor()
c = cur.execute('SELECT * FROM some')
u_data = c.fetchall()
Each row is a set of data.
The data is taken from the first row and data from column_1 goes to the place of XXX1, data from column_2 goes to the place of XXX2 and data from column_3 goes to the place of XXX3...
After that I should get the data from the original array (template) + data taken from the database...then this dict should be committed to DB and the loop should go on until the data from the DB and every time commit my new dict to DB...
Now I have some code:
import sqlite3
from itertools import product
a = {"phone_number": "XXX","phone_number_country": "XXX","text": "XXX"}
con = sqlite3.connect('dab')
cur = con.cursor()
c = cur.execute('SELECT * FROM some')
u_data = c.fetchall()
s = list(u_data)
b = list(zip(*u_data))
out = product(*b)
tout =list(out)
i = 0
for elem in b:
b[i] = elem
a["phone_number"] = elem[0]
a["phone_number_country"] = elem[1]
a["text"] = elem[2]
print(a)
and in console i have this:
{'text': 'phone_number31', 'phone_number_country': 'phone_number21', 'phone_number': 'phone_number11'}
{'text': 'phone_number_c32', 'phone_number_country': 'phone_number_c22', 'phone_number': 'phone_number_c12'}
{'text': 'text33', 'phone_number_country': 'text23', 'phone_number': 'text13'}
It should be:
{"phone_number": "phone_number11","phone_number_country": "phone_number_c12","text": "text13"}
{"phone_number": "phone_number21","phone_number_country": "phone_number_c22","text": "text23"}
{"phone_number": "phone_number31","phone_number_country": "phone_number_c32","text": "text33"}
Dictionaries in python do not maintain the insertion order by default. You need ordered dictionary for this.
I have reproduced a part of your code below:
import collections
a = collections.OrderedDict()
for elem in b:
b[i] = elem
a["phone_number"] = elem[0]
a["phone_number_country"] = elem[1]
a["text"] = elem[2]
print(a)
Answer here:
a = {"phone_number": "XXX","phone_number_country": "XXX","text": "XXX"}
con = sqlite3.connect('dab')
cur = con.cursor()
c = cur.execute('SELECT * FROM some')
u_data = c.fetchall()
s = list(u_data)
i = 0
for elem in s:
s[i] = elem
a["phone_number"] = elem[0]
a["phone_number_country"] = elem[1]
a["text"] = elem[2]
Related
def SelectData(self):
query = "Select * from python_training.rules"
curr = self.con.cursor()
curr.execute(query)
for row in curr:
result = row
print(result)
The above function returns :
(1, 'CU_GFC_ID', '11A')
(2, 'GFCID', '10')
(1, 'GFCID', '11')
How to make each row as a individual list object?
Check below code convert result to list:
import pandas as pd
import sqlite3
df = pd.DataFrame({'col1':[1,2], 'col2':['a','b']})
conn = sqlite3.connect(':memory:')
df.to_sql(name='df', con=conn, index=False)
print('{:9} | {:^9}'.format('tuple', 'list'))
def SelectData():
query = "Select * from df"
curr = conn.cursor()
curr.execute(query)
for row in curr:
result = list(row)
print('{:9} | {:9}'.format(str(row), str(result)))
SelectData()
Output:
from dataa import *
dataman = mysql.connector.connect(host='localhost', user='root', passwd='12345678', database='basictest')
databoy = dataman.cursor()
with open('data.txt') as g:
data = g.read().split('\n')
vl = ['']
vm = ['SELECT Name FROM Patient', 'SELECT DOB FROM Patient', 'SELECT Email FROM Patient',
'SELECT Username FROM Patient', 'SELECT Password FROM Patient', 'SELECT Mobile FROM Patient']
x = 0
for j, i in zip(data, vm):
if
vl[0] = j
x += 1
databax = ("INSERT INTO Patient(Name) VALUES(%s)")
d = [('a')]
databoy.execute(databax, d)
dataman.commit()
print(x)
I want to append each value of J to each column seperately. Only thing I can do is that append all of that to same column . on addition of other column, it throws an error. What can I do. No use of classes will be apppreciated. Can I select each column seperately and update it each time I update the form. This is the registration form of a application
I had a query that should return all permittedUserId when userId matched with what was supplied my the user. I wanted to use the result of the query for a different query and noticed I kept getting the same output.
sql = "SELECT permittedUserId FROM PermittedSharedUSer WHERE PermittedSharedUSer.userId = %s"
Here is what the table looks like
Why do I get this output?
[{'num': 3}, {'num': 3}, {'num': 3}, {'num': 3}]
The output I want should be number 7,6,2,3, not 3,3,3,3
Here's the whole code:
self.ensureConnected()
applicationUser = (content['userID'], )
sql = "SELECT permitedUserId FROM PermittedSharedUSer WHERE PermittedSharedUSer.userId = %s"
crows = self.cursor.execute(sql, applicationUser)
result = self.cursor.fetchall()
if(len(result) > 0 ):
d = collections.OrderedDict()
objects_list = []
for row in result:
d['num'] = row[0]
#sqlname = "SELECT name , username FROM Users WHERE Users.id=%s"
#valname = (row[0],)
#self.cursor.execute(sqlname,valname)
#resultName = self.cursor.fetchall()
#for row2 in resultName:
# d['name'] = row2[0]
# d['username'] = row2[1]
objects_list.append(d)
return (json.dumps(dict(data = objects_list), default=str), 200)
elif(crows ==None):
return (json.dumps(dict(data = "empty")), 200)
Here's a sample table which I created in SQL
and the code to fetch the data from it
import mysql.connector
db = mysql.connector.connect(host='localhost',user='root',passwd='5548',database='test')
cursor =db.cursor()
n='1'
cursor.execute("select permission from test where userid = %s",(n,))
v = cursor.fetchall()
for i in v:
print(i[0],end=" ")
and the output is
7 6 2 4
Hence, the way you are establishing the connection and retrieving the data is fine.
Looking at the for loop - I can see the probable error
objects_list.append(d)
should be
objects_list.append(d['num'])
The code should look like this
applicationUser = (content['userID'], )
sql = "SELECT permitedUserId FROM PermittedSharedUSer WHERE PermittedSharedUSer.userId = %s"
crows = self.cursor.execute(sql, applicationUser)
result = self.cursor.fetchall()
if(len(result) > 0 ):
d = collections.OrderedDict()
objects_list = []
for row in result:
d['num'] = row[0]
#sqlname = "SELECT name , username FROM Users WHERE Users.id=%s"
#valname = (row[0],)
#self.cursor.execute(sqlname,valname)
#resultName = self.cursor.fetchall()
#for row2 in resultName:
# d['name'] = row2[0]
# d['username'] = row2[1]
objects_list.append(d['num'])
I've some code to input data into list, how can I import data in my list into database?
import psycopg2
import random
import string
import time
conn = psycopg2.connect(host="localhost",database="postgres", user="postgres", password="potatona1")
cursor = conn.cursor()
FullChar = 'CEFLMPRTVWXYK0123456789#'
total = 4
count = 10
count = int(count)
for i in range(1000):
for x in range(total):
unique_code = ''.join(random.sample(FullChar, count - 1)) + '#'
unique_code = ''.join(random.sample(unique_code, len(unique_code)))
list(unique_code)
postgres_insert_query = """ INSERT INTO employees (id_employee, name) VALUES (%s,%s)"""
record_to_insert = (1, unique_code)
cursor.execute(postgres_insert_query, record_to_insert)
conn.commit()
count = cursor.rowcount
print (count, "Record inserted successfully into mobile table")
I want import 1000 data to postgresql with python.
i just trying this, and it works
conn = psycopg2.connect(host="192.168.13.10",database="postgres", port="5432", user="postgres", password="potatona1")
cursor = conn.cursor()
FullChar = 'CEFLMPRTVWXYK0123456789'
total = 1000
count = 10
count = int(count)
entries = []
bcd = ""
flg = ""
rll = ""
def inputDatabase(data):
postgres_insert_query = """INSERT INTO unique_code(unique_code, barcode, flag, roll) VALUES (%s,%s,%s,%s)"""
cursor.executemany(postgres_insert_query, data)
conn.commit()
for i in range(5):
for x in range(total): # banyaknya code yang di print
unique_code = ''.join(random.sample(FullChar, count - 1))
unique_code = ''.join(random.sample(unique_code, len(unique_code)))
entry = (unique_code, bcd, flg, rll)
entries.append(entry)
inputDatabase(entries)
print(i)
count = cursor.rowcount
print (count, "Record inserted successfully into mobile table")
i use a function calculate servers prices so i made a function which retrieve a defalut prices of a server components and calculate server price for each server exsit in my DB but i try to run this function, i get this error:
function.py
import MySQLdb
def calculations_metric (param) :
db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
cursor = db.cursor()
sql = "SELECT * FROM examples_calculationsmetric"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
RAM_prices = int(row[1])
Core_prices = int(row[2])
HHD_SATA_prices =int(row[3])
HHD_SSD_prices =int(row[4])
CPU_priority = int(row[5])
Avaibility = int(row[6])
db.close()
db1 = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
cursor1 = db1.cursor()
sql1 = "SELECT * FROM examples_servercomponents WHERE id ='%d'" %(param)
cursor1.execute(sql1)
results1 = cursor1.fetchall()
for row in results1:
if row[6] == 'SATA':
Core_price = int(row[2]) * Core_prices # the error is here
Priority_price = int(row[3]) * CPU_priority
RAM_price = int(row[4]) * RAM_prices
HDD_price = int(row[5]) * HHD_SATA_prices
Availibility_price = int(row[7])*Avaibility
elif row[6] == 'SSD':
Core_price = int(row[2]) * Core_prices
Priority_price = int(row[3]) * CPU_priority
RAM_price = int(row[4]) * RAM_prices
HDD_price = int(row[5]) * HHD_SSD_prices
Availibility_price = int(row[7])*Avaibility
price = Core_price + Priority_price + RAM_price + HDD_price + Availibility_price
db1.close()
return price
i don't get what is the error so if can anyone help i will be so greatful
When your SELECT * FROM examples_calculationsmetric doesn't return any results, Core_prices is never set (nor are the other variables in that loop).
Python names do not exist until assigned to, so if results is an empty list, the names inside the for loop never get assigned to and thus do not exist by the time you loop over results1 later on.
You could set default values for those names as a work-around:
RAM_prices = 0
Core_prices = 0
HHD_SATA_prices = 0
HHD_SSD_prices = 0
CPU_priority = 0
Avaibility = 0
to at least ensure that they are defined.