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.
Related
I tried to create table in my database and add PRIMARY KEY to my table by using sqlite3 library, But sqlite3 did not understand NULL
this my code:
import sqlite3
def connect():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)")
conn.commit()
conn.close()
def insert(title,author,year,isbn):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("INSERT INTO book VALUES (NULL,?,?,?,?)",(title,author,year,isbn))
conn.commit()
conn.close()
view()
def view():
conn=sqlite3.connect('books.db')
cur=conn.cursor()
cur.execute("SELECT \* FROM book")
rows=cur.fetchall()
conn.close()
return rows
connect()
insert('anybook','anyperson',1918,6384515345)
print(view())
I expected the output to be
[(1,'anybook','anyperson',1918,6384515345)]
But it was:
Traceback (most recent call last):
File "e:\CORSES\The Python Mega Course\000. Projects\APPs\4. BookStore\Book Store\BackEnd.py", line 28, in <module>
insert('anybook','anyperson',1918,6384515345)
File "e:\CORSES\The Python Mega Course\000. Projects\APPs\4. BookStore\Book Store\BackEnd.py", line 13, in insert
cur.execute("INSERT INTO book VALUES (NULL,?,?,?,?)",(title,author,year,isbn))
sqlite3.OperationalError: table book has 4 columns but 5 values were supplied
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
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
I get the following error when I run my code and I don't know why:
Traceback (most recent call last):
File "python", line 27, in <module>
File "python", line 25, in members_of_circles
sqlite3.OperationalError: no such column: circleCat.name
the code :
import sqlite3
con = sqlite3.connect(":memrory:")
cur = con.cursor()
def creat_tables () :
cur.execute("CREATE table circleCat (id INTEGER PRIMARY KEY, name TEXT,
description TEXT)")
cur.execute("CREATE table members( id INTEGER PRIMARY KEY, name TEXT, level
TEXT, crcl TEXT)")
def add_a_member(name, level, crcl):
cur.execute("INSERT INTO members (name, level, crcl) VALUES (?, ?, ?)" ,
(name, level, crcl));
def add_a_circle(name, description):
cur.execute("INSERT INTO circleCat (name, description) VALUES (?, ?)" ,
(name, description));
creat_tables ()
add_a_circle("Gaming", "for Gaming")
add_a_member("hossam", "beginner", "Gaming")
def members_of_circles():
cur.execute("SELECT name FROM members WHERE members.crcl =
circleCat.name")
members_of_circles()
Your select query is wrong. Try this:
def members_of_circles():
cur.execute("SELECT m.name FROM members m, circleCat c WHERE m.crcl = c.name")
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";