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")
Related
In the line:
for row in cursor.execute("SELECT classCapacity FROM tblClass1 WHERE classID = ?", [classID]):
I am getting a binding error saying the statement uses one and six have been supplied and have been stuck trying to fix it for hours now any suggestions are welcome.
def addBooking():
def CostCalculation():
Cost = 0
Validation = False
sqlite3.connect("TestProject.db")
cursor = connection.cursor()
for row in cursor.execute("SELECT classCost from tblClass1 WHERE classID =?", cClassID):
Validation = True
cost = row[0]
Cost = (int(cost))
return Cost, Validation
connection = sqlite3.connect("TestProject.db")
curosr = connection.cursor()
cClientID = getID(clientID.get())
cClassID = classID.get()
cDate = bookingDate.get()
cCost, costValidation = CostCalculation()
bookingRec = [cClientID, cClassID, cDate, cCost]
for row in cursor.execute("SELECT classCapacity FROM tblClass1 WHERE classID = ?", [classID]):
maxCap = row[0]
capacity = 0
for row in cursor.execute("SELECT * FROM tblBooking WHERE classID = ? and bookingDate =?", [cClassID, cDate]):
capacity = capacity + 1
if capacity < maxCap:
cursor.execute("INSERT INTO tblBooking VALUES(Null,?,?,?,?)", bookingRec)
connection.commit()
connection.close()
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
def ConnecttoCurrency():
conn = sqlite3.connect('E:\python\Player_Currency.sqlite')
print('Right before conn')
with conn:
print('I have entered currency')
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("SELECT * FROM Player_Curren")
rows = cur.fetchall()
for row in rows:
global primecolumn, Currency_Name, amount,money
print('im in Row of rows')
primecolumn, Currency_Name, amount = (
row["pkcolumn"], row["Currency_Name"], row["amount"])
money = amount
print('HEY I GOT INTO THE ROW LOOP')
print(amount)
return money
This isn't out putting print im in row of rows, but
def DeleteItemAndReturnSilver():
conn = sqlite3.connect('E:\python\Player_Inv_Database.sqlite')
with conn:
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("SELECT * FROM Player_Inv")
rows = cur.fetchall()
money = 0
for row in rows: # gets Item from monster loot table
print('Im in delteitemrows')
global Item_c, Item_N, Pr, Number_Of_I, money
Item_c, Item_N, Pr, Number_Of_I = (
row["pkcolumn"], row["Item_Name"], row["Price"], row["Number_Of_Item"])
money = Pr + money
query = 'DELETE FROM Player_Inv WHERE pkcolumn=?'
cur.execute(query, (Item_column,))
print(money)
return money
but this works, and prints im in delete itemsrow, Im lost and its confusing me because its making no since. Thanks for helping
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]
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.