Python Postgres Insert into error - python

Hello all I have to make a bulk entry to my postgresql table from python for loop code. I have tried all possible means to enter the data. But I was unable to to do it.
data = count,ipaddress,asn_value,asno,aso,sock_value,sock,datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
print (data)
cur.execute('insert into dataoldnew values (%s,%s,%s,%s,%s,%s,%s,%s)',data)
print("Records created successfully")
conn.close()
Debug
data= (1, '217.76.156.252', 1, 8560, '1&1 Internet SE', 0, 0, '2018-06-06 11:35')
Error
Exception in callback task2() at mining.py:43
handle: <Handle task2() at mining.py:43>
Traceback (most recent call last):
File "/usr/lib/python3.5/asyncio/events.py", line 125, in _run
self._callback(*self._args)
File "mining.py", line 31, in wrapper
ret = func(*args, **kwargs)
File "mining.py", line 149, in task2
cur.execute('insert into dataoldnew values (%s,%s,%s,%s,%s,%s,%s,%s)',data)
psycopg2.DataError: invalid input syntax for integer: "217.76.156.252"
LINE 1: insert into dataoldnew values (1,'217.76.156.252',1,8560,'1&...
^
I have a table in postgresql.
Postgres Table Schema
-- Table: public.dataoldnew
-- DROP TABLE public.dataoldnew;
CREATE TABLE public.dataoldnew
(
index bigint,
idtemp bigint,
ipaddress text,
"timestamp" text,
values_asn bigint,
values_aso text,
values_host_name text,
values_host_name_true_false bigint
)
WITH (
OIDS=FALSE
);
ALTER TABLE public.dataoldnew
OWNER TO aditya;
-- Index: public.ix_dataoldnew_index
-- DROP INDEX public.ix_dataoldnew_index;
CREATE INDEX ix_dataoldnew_index
ON public.dataoldnew
USING btree
(index);
Thanks Advance

Related

Syntax Error in SQLite Near ORDER (sqlite3.OperationalError)

I think this is a rookie mistake. I tried several hours but couldn't find a solution.
I heard that SQLite supports multithreaded access to a file. So I created my first database with multiple tables in Python:
def create_table(page):
con = connect('emails.db')
cur = con.cursor()
try:
cur.executescript(f'''
CREATE TABLE {page} (
id INTEGER,
email VARCHAR,
password VARCHAR,
time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
''')
con.commit()
except:
pass
con.close()
Now to my problem what I want to do:
Move first row of table e. g. fremdgehen to fremdgehen_used
do something
Delete first row of fremdgehen
repeat
What my program does:
Move first row of fremdgehen to fremdgehen_used
Do something
It's not deleting the first row of "fremdgehen" and only moves one row to "fremdgehen_used", instead it gives following error:
Exception in thread
Thread-1reifer6:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "c:\Users\Administrator\Desktop\de_1\v2\sub_bot\main.py", line 92, in main
delete_table_row(page)
File "c:\Users\Administrator\Desktop\de_1\main_bot\data.py", line 62, in delete_table_row
cur.execute(f'DELETE FROM {page} ORDER BY id LIMIT 1')
sqlite3.OperationalError: near "ORDER": syntax error
*This message three times because three threads are running
My Code:
Move first row of table e. g. fremdgehen to fremdgehen_used
def move_table(page):
# page is "fremdgehen"
con = connect('emails.db')
cur = con.cursor()
cur.execute(f'INSERT INTO {page}_used SELECT * FROM {page} LIMIT 1')
con.commit()
con.close()
Do something
Delete first row of fremdgehen
def delete_table_row(page):
# page is "fremdgehen"
con = connect('emails.db')
cur = con.cursor()
cur.execute(f'DELETE FROM {page} ORDER BY id LIMIT 1')
con.commit()
con.close()
I believe that the query to delete the first line is wrong. Maybe this would work out better:
Delete from fremdgehen where id IN (Select id from fremdgehen limit 1);
Stolen from: https://stackoverflow.com/a/10381812/10110813

Error in executing mysql code with python

Hey I'm making my project and I've written this code. But this is giving me this error. It would be very helpful for me if you can help me with tis to find the solution.
here's my code.
import mysql.connector as cntr
db = cntr.connect(host = 'localhost' , user = 'root' , passwd = '2004')
db.autocommit = True
cur = db.cursor()
cur.execute("DROP DATABASE IF EXISTS shop_management")
cur.execute("create database if not exists shop_management")
cur.execute("use shop_management")
cur.execute("""create table if not exists stock
(Book_No bigint primary key,
Book_Name varchar(255),
Author varchar(255),
Publisher varchar(255),
Cost_per_Book float,
Available_Stock bigint,
qty_purchased bigint,
purchased_on date)""")
cur.execute("create table if not exists users(username varchar(255) , password varchar(255) , check (username <> 'ADMIN'))")
cur.execute("create table if not exists purchased (Book_no bigint , purchased_on date , foreign key(Book_no) references stock(Book_No))")
cur.execute("create unique index Book_Index on stock(Book_No)")
cur.execute("insert into users values('ADMIN' , 'admin#123')")
print("Database and Tables created successfully")
c = input("Press any key to continue-----> ")
cur.close()
db.close()
And it's giving me this error
Traceback (most recent call last):
File "D:\CBSE 12\cs projects\Tables_in_mysql.py", line 20, in <module>
cur.execute("insert into users values('ADMIN' , 'admin#123')")
File "C:\Python 37\lib\site-packages\mysql\connector\cursor.py", line 568, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Python 37\lib\site-packages\mysql\connector\connection.py", line 846, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Python 37\lib\site-packages\mysql\connector\connection.py", line 656, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.DatabaseError: 3819 (HY000): Check constraint 'users_chk_1' is violated.

Create table error in MYSQL database using Python

I wanted to create a database of my data which have been stored in files .For this I used file handling to read data from the stored files and input into the table of my database. But it shows error given below.
Is it the correct way to switch data storage option from files to database.
The error occured is given below -:
Traceback (most recent call last):
File "C:/Users/sarth/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/scratch_2.py", line 61, in <module>
indatabase()
File "C:/Users/sarth/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/scratch_2.py", line 54, in indatabase
cur.execute ("SELECT * FROM PETROL")
File "C:\Users\sarth\AppData\Local\Programs\Python\Python38-32\lib\site-packages\mysql\connector\cursor.py", line 566, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Users\sarth\AppData\Local\Programs\Python\Python38-32\lib\site-packages\mysql\connector\connection.py", line 537, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Users\sarth\AppData\Local\Programs\Python\Python38-32\lib\site-packages\mysql\connector\connection.py", line 436, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1146 (42S02): Table 'pump.petrol' doesn't exist
Failed to create table in MySQL: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AMOUNT FLOAT ,QUANTITY FLOAT ,Year VARCHAR(10) ,Date DATE' at line 1
This is the code which reads data from files and then inputs in the database.
import pickle
def indatabase() :
# FOR PETROL
import mysql.connector
try :
conn = mysql.connector.connect (host='localhost' ,database='PUMP' ,user='asdad' ,
password='11234567')
cur = conn.cursor ( )
cur.execute ("DROP TABLE IF EXISTS PETROL")
cur.execute ("CREATE TABLE PETROL ( id INT AUTO_INCREMENT PRIMARY KEY ,
AMOUNT FLOAT ,QUANTITY FLOAT ,Year VARCHAR(10) ,Date DATE")
fp1 = open ("D:/Python/petrol/pdate/pdate.txt" , "rb+")
while True:
try :
pdate = pickle.load (fp1)
cur.execute ("INSERT INTO PETROL Date VALUES(?)" , (pdate))
except EOFError :
fp1.close()
fp3 = open ("D:/Python/petrol/pyear/pyear.txt" , "rb+")
while True:
try :
pyear = pickle.load (fp3)
cur.execute ("INSET INTO PETROL Year VALUES(?)" , (pyear))
except EOFError :
fp3.close()
fp4=open ("D:/Python/petrol/petrolamt/petrolamt.txt" , "rb+")
while True:
try :
pamt = pickle.load (fp4)
cur.execute ("INSERT INTO PETROL Amount VALUES(?)" , (pamt))
except EOFError :
fp4.close()
fp5 = open ("D:/Python/petrol/petrolqty/petrolqty.txt" , "rb+")
while True:
try :
pqty = pickle.load (fp5)
cur.execute ("INSERT INTO PETROL Quantity VALUES(?)" , (pqty))
except EOFError :
fp5.close()
conn.commit ( )
except mysql.connector.Error as error :
print ("Failed to create table in MySQL: {}".format (error))
finally :
if (conn.is_connected ( )) :
cur.execute ("SELECT * FROM PETROL")
for i in cur :
print (i)
cur.close ( )
conn.close ( )
print ("MySQL connection is closed")
indatabase()
on this line
CREATE TABLE PETROL...
you are missing the closing parenthesis after Date DATE

Python "commands out of sync" error message when I am trying to import csv to MYSQLdb

I've get this error message when i want to execute my sqldb code in Python 2.7:
Traceback (most recent call last):
File "C:/Python27/air18-mysql.py", line 52, in <module>
cursor.execute(query)
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 221, in execute
if not self._defer_warnings: self._warning_check()
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 107, in _warning_check
warnings = self._get_db().show_warnings()
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 371, in show_warnings
self.query("SHOW WARNINGS")
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 282, in query
_mysql.connection.query(self, query)
ProgrammingError: (2014, "Commands out of sync; you can't run this command now")
The relevant pieces of my code are as follows:
connection = MySQLdb.connect(host='localhost',
user='root',
passwd='1234',
db='database')
cursor = connection.cursor()
query = """
CREATE TABLE `test` (
`A` varchar(100) DEFAULT NULL,
`B` varchar(100) DEFAULT NULL,
`C` varchar(100) DEFAULT NULL,
`D` varchar(100) DEFAULT NULL,
`E` varchar(100) DEFAULT NULL,
`F` varchar(100) DEFAULT NULL,
`G` varchar(100) DEFAULT NULL,
`ID` int(10) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8"""
cursor.execute(query)
connection.commit()
cursor.close()
connection = MySQLdb.connect(host='localhost',
user='root',
passwd='1234',
db='database')
cursor = connection.cursor()
query = """ load data local infile 'C:/Python27/output.csv'
into table test
character set latin1
fields terminated by ';'
enclosed by '"'
lines terminated by '\r\n';
ignore 1 lines;
"""
cursor.execute(query)
connection.commit()
cursor.close()
Anybody know what I'm doing wrong?
I tried it with another csv too and it worked.
Maybe there is a problem in my csv file or i can't imagine what is the problem with this.
Here one part of my csv file (in NotePad++):
"apple apricot";" avocado";"blackcurrant (fruit)-";"blackberry";"blueberry (fruit) ";"";"lemon lime"
"quince pear";" banana";"papaya (fruit)-";"orange";"passion fruit (fruit) ";"";"pineapple watermelon"
after lemon lime and pineapple watermelon, you are missing a semi colon. Try with this:
"apple apricot";" avocado";"blackcurrant (fruit)-";"blackberry";"blueberry (fruit) ";"";"lemon lime";"quince pear";" banana";"papaya (fruit)";"orange";"passion fruit (fruit) ";"";"pineapple watermelon";

Inserting values in MySQL table using Python

I have a Bank table in MySQL with the following schema:
`User_id` int(11) NOT NULL AUTO_INCREMENT,
`Amount` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`User_id`)
I am trying to take Amount as input and enter a record in the table using Python. I run the following code for the same:
print " enter the bank amount"
Amount = raw_input()
cursor.execute('''INSERT into Bank (Amount)
values (%d)''',
(Amount))
cursor.execute('commit')
But, it shows following error:
Traceback (most recent call last):
File "create_user.py", line 23, in <module>
(Amount))
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute
query = query % tuple([db.literal(item) for item in args])
TypeError: %d format: a number is required, not str
raw_input() returns a string:
If the prompt argument is present, it is written to standard output
without a trailing newline. The function then reads a line from input,
converts it to a string (stripping a trailing newline), and returns
that.
>>> test = raw_input()
1
>>> test
'1'
>>> type(test)
<type 'str'>
You need to cast it to int (according to the Amount column type):
amount = int(raw_input()) # TODO: handle exceptions?
cursor = db.cursor()
cursor.execute("""
INSERT INTO
Bank (Amount)
VALUES
(%d)
""", (amount, ))
db.commit()

Categories