I can't delete data multiple in mysql from python - python

I made input 2 value row and num when input data so program throw Rollback not work if-else and thank for help
#!/usr/bin/python
import mysql.connector
conn = mysql.connector.connect(host="",user="",passwd="",db="")
cursor = conn.cursor()
try:
row = raw_input("InputNameRow : ")
num = int(input("InputNumber 1-10 : "))
if num <= 10:
sql1 = "SELECT * FROM dt WHERE '%s' = '%d' " %(row,num)
cursor.execute(sql1)
data = cursor.fetchall()
print(data[0])
sqlde = "DELETE FROM dt WHERE '%s' = '%d' " %(row,num)
cursor.execute(sqlde, (num))
print "DELETE SUCESS"
conn.commit()
else:
print "Data Empty"
except:
conn.rollback()
print "Input Error"
conn.close()

Try :
cursor.execute(sqlde)
instead of
cursor.execute(sqlde, (num))

Related

executing a sql query using python

I'm trying to create a small python app to extract data from specific table of database.
The extracted rows have to be between CREATION_DATETIME specified by user.
Heres the code:
startdate = input("Prosze podac poczatek przedzialu czasowego (format RRRR-MM-DD GG:MM:SS): ")
enddate = input("Prosze podac koniec przedzialu czasowego (format RRRR-MM-DD GG:MM:SS): ")
query = "SELECT * FROM BRDB.RFX_IKW_MODIFY_EXEC_ORDER_CANCEL_LOG WHERE CREATION_DATETIME between '%s' and '%s' ORDER BY CREATION_DATETIME DESC;"
tuple1 = (startdate, enddate)
cursor.execute(*query, (tuple1,))
records = cursor.fetchall()
print("Total number of rows in table: ", cursor.rowcount)
print(records)
I'm not much of developer and I'm stuck at error "TypeError: CMySQLCursorPrepared.execute() takes from 2 to 4 positional arguments but 104 were given" in various counts, depends on how I try to modify the code.
Could you guys help me out in specyfing that query correctly?
Thank you in advance.
Tried various tutorial about parametrized query but with no luck.
You're starring the query, making it an iterable of the characters making up the string, which probably isn't what you meant (i.e., you should emove the * operator). In addition, tuple1 is already a tuple, you shouldn't enclose it inside another tuple:
cursor.execute(query, tuple1)
# Remove the *-^
# Use tuple1 directly-^
here is the full code
import mysql.connector
from mysql.connector import Error
try:
print("Laczenie z baza danych....")
connection = mysql.connector.connect(host='',
port='',
database='',
user='',
password='')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Wersja servera MySQL:", db_Info)
cursor = connection.cursor(prepared=True)
cursor.execute("select database();")
record = cursor.fetchone()
print("Pomyslnie polaczono z baza danych: ", record)
except Error as e:
print("Blad polaczenia!", e)
quit()
try:
startdate = input("Prosze podac poczatek przedzialu czasowego (format RRRR-MM-DD GG:MM:SS): ")
enddate = input("Prosze podac koniec przedzialu czasowego (format RRRR-MM-DD GG:MM:SS): ")
query = "SELECT * FROM BRDB.RFX_IKW_MODIFY_EXEC_ORDER_CANCEL_LOG WHERE CREATION_DATETIME between '%s' and '%s' ORDER BY CREATION_DATETIME DESC;"
tuple1 = (startdate, enddate,)
cursor.execute(query, tuple1)
records = cursor.fetchall()
print("Fetching each row using column name")
for row in records:
message_id = row["MESSAGE_ID"]
executable_order_id = row["EXECUTABLE_ORDER_ID"]
creation_datetime = row["CREATION_DATETIME"]
message_type = row["MESSAGE_TYPE"]
message_status = row["MESSAGE_STATUS"]
print(message_id, executable_order_id, creation_datetime, message_status)
except mysql.connector.Error as e:
print("Error reading data from MySQL table", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")

Not able to show sqlite3(back end) error on Tkinter(front end)

I am working on a small project which is a school management project which simply does add, update, delete a student from the database
For the front end I am using Tkinter and for backend I am using sqlite3
Here I have roll number as the primary key, when I try to add the same roll number again it doesn't add into the database, and also it doesn't return anything on the front end.
So, I try to add showerror on the front end from the already exists roll number but it doesn't give me an error on the front end. For update and delete it showing an error on the font-end properly but for add only it is not working
Here is the code of save function(which is not working properly):
def save1():
con = None
try:
Connection.cursor
con = connect("pypro.db")
try:
rollno = int(enteno.get())
name = entename.get()
marks = int(entmrk.get())
except:
messagebox.showerror("EMPTY","enter the entry properly")
try:
if len(name)<2:
return messagebox.showerror("ERROR","name should contain minimum 2 alphabets")
if marks > 101:
return messagebox.showerror("ERROR","marks should be less the 100")
finally:
entmrk.delete(0,END)
cursor = con.cursor()
sql = "insert into entry values ('%d','%s','%d')"
args = (rollno,name,marks)
cursor.execute(sql%args)
if cursor.rowcount == 1:
con.commit()
msg = "RECORD Inserted"
messagebox.showinfo("Inserted",msg)
else :
msg2 = "record does exists"
return messagebox.showerror("ERROR",msg2)
enteno.delete(0,END)
entename.delete(0,END)
entmrk.delete(0,END)
enteno.focus()
except DatabaseError as e:
con.rollback()
finally:
if con is not None:
con.close()
Here is the code of update function(which is working properly):
def update():
con = None
try:
Connection.cursor
con = connect("pypro.db")
try:
name = enteupname.get()
marks = int(entupmrk.get())
except:
messagebox.showinfo("EMPTY","enter the entry properly")
try:
if len(name)<2:
return messagebox.showerror("ERROR","name shoul contain minimum 2 alphabets")
if marks >= 100:
return messagebox.showerror("ERROR","marks should be less the 100")
finally:
entmrk.delete(0,END)
rollno = int(entupeno.get())
cursor = con.cursor()
sql = "update entry set name='%s'where rollno= '%d'"
args = (name,rollno)
cursor.execute(sql % args)
sql1 = "update entry set marks='%d' where rollno='%d'"
args1 = (marks,rollno)
cursor.execute(sql1%args1)
if cursor.rowcount == 1:
con.commit()
msg = "RECORD UPDATED"
messagebox.showinfo("update",msg)
else:
msg = "record does not exists"
messagebox.showerror("ERROR",msg)
entupeno.delete(0,END)
enteupname.delete(0,END)
entupmrk.delete(0,END)
entupeno.focus()
except DatabaseError as f:
con.rollback()
finally:
if con is not None:
con.close()
Please tell me if more information need to be added in this question.

python to write data into table error

write python program to create a mysql table and insert data into this table,the program is as follows:
def pre_data_db_manage(type,data):
conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="********", db="facebook_info",charset="utf8")
cur = conn.cursor()
if type == "pre_davi_group_members_data":
is_exist_table_sql = "SHOW TABLES LIKE 'fb_pre_davi_group_members_posts'"
if cur.execute(is_exist_table_sql) == 0:
create_table_sql = '''CREATE TABLE fb_pre_davi_group_members_posts (id bigint not null primary key auto_increment,userID bigint,userName varchar(128),userURL varchar(256),
postTime varchar(128),postText text,postTextLength int,likesCount int,sharesCount int,commentsCount int,postTextPolarity varchar(64),postTextSubjectivity varchar(64))'''
cur.execute(create_table_sql)
r = re.compile(r'^[a-zA-Z0-9]')
for item in data:
if "'" in item["PostText"]:
item["PostText"] = item["PostText"].replace("'"," ")
if "\\" in item["PostText"]:
item["PostText"] = item["PostText"].replace("\\","\\\\")
for i in item["PostText"]:
result = r.match(i)
if result == None:
print("in re")
item['PostText'] = item['PostText'].replace(i, ' ')
if "nan" in item["SharesCount"]:
item["SharesCount"] = 0
if "nan" in item["LikesCount"]:
item["LikesCount"] = 0
if "nan" in item["CommentsCount"]:
item["CommentsCount"] = 0
if "nan" in item["PostTextLength"]:
item["PostTextLength"] = 0
item["PostTextLength"] = int(item["PostTextLength"])
item["LikesCount"] = int(item["LikesCount"])
item["SharesCount"] = int(item["SharesCount"])
item["CommentsCount"] = int(item["CommentsCount"])
if type == "pre_davi_group_members_data":
insert_sql = '''INSERT INTO fb_pre_davi_group_members_posts (userID,userName,userURL,
postTime,postText,postTextLength,likesCount,sharesCount,commentsCount,postTextPolarity,postTextSubjectivity) VALUES
({0},"{1}",'{2}','{3}','{4}',{5},{6},{7},{8},{9},{10})'''.format(item["UserID"],item["UserName"],item["UserURL"],item["PostTime"],item["PostText"],item["PostTextLength"],item["LikesCount"],item["SharesCount"],item["CommentsCount"],item["PostTextPolarity"],item["PostTextSubjectivity"])
print(insert_sql)
try:
cur.execute(insert_sql)
except Exception as e:
print("insert error")
continue
cur.close()
conn.commit()
conn.close()
and write call statement as follows:
type = "pre_davi_group_members_data"
pre_data_db_manage(type, df_list)
however,when execute this program, found that no data have been inserted into table:fb_pre_davi_group_members_posts,
in the mysql order line, write:
select count(*) from fb_pre_davi_group_members_posts;
the result is 0
could you please tell me the reason and how to solve it

If value true but null not work

I made program is input number and delete data in mysql. but run program error then report sql1 Syntax Error\i change true
#!/usr/bin/python
import mysql.connector
conn = mysql.connector.connect(host="",user="",passwd="",db="")
cursor = conn.cursor()
try:
num = int(input("InputNumber 1-10 : "))
if num <= 10:
if num == null: //if null print false
sql1 = "SELECT user1 FROM dt WHERE user1 = '%d' " %(num)
cursor.execute(sql1)
data = cursor.fetchall()
print(data[0])
sqlde = "DELETE FROM dt WHERE user1 = '%d' " %(num)
cursor.execute(sqlde, (num))
print "DELETE SUCESS"
conn.commit()
else:
print "Data Empty"
except:
conn.rollback()
conn.close()
num = int(input("InputNumber: ")) <- don't forguet to close it
I'm not sure about the %i, I always see using %d for Integer and %s to strings
But, you also have one problem into your query, SQL Injection
So to avoid this, try something like this
sql1 = "DELETE FROM dt WHERE user1 = ?"
try:
cursor.execute(sql1, (num))
print "DELETE SUCECC"
conn.commit()
except:
conn.rollback()
print "ERROR DELETE"
you can check about question mark here or here and understand why you should bind your values

Python CGI error trying to execute a sqlite command

I'm not sure why it says that the table ajax_exmaple does not exist... I check sqlite3 to see that the database and the tables along w/ their corresponding datas are all there. Any ideas?
When I try to execute this command:
query_result = c.execute(query, (sex, age, wpm))
...I get:
<class 'sqlite3.OperationalError'>: no such table: ajax_example
args = ('no such table: ajax_example',)
message = 'no such table: ajax_example'
This is my complete code:
#!C:\python27\python.exe
import cgi, cgitb, sqlite3
cgitb.enable()
print "Content-type: text/html"
print ""
conn = sqlite3.connect('../htdocs/ajax_ex.db')
c = conn.cursor()
# Capture URL query
form = cgi.FieldStorage()
age = form.getvalue('age')
sex = form.getvalue('sex')
wpm = form.getvalue('wpm')
# Build SQL
query = "SELECT * FROM ajax_example WHERE ae_sex = ?"
if(isinstance(age, int)):
query += " AND ae_age <= ?"
if(isinstance(wpm, int)):
query += " AND ae_wpm <= ?"
# Execute query
query_result = c.execute(query, (sex, age, wpm))
conn.close()
# Build result string
display_string = '''
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Sex</th>
<th>WPM</th>
</tr>'''
# Insert a new row in the table for each person returned
for row in query_result:
display_string += "<tr>"
display_string += "<td>row['ae_name']</td>"
display_string += "<td>row['ae_age']</td>"
display_string += "<td>row['ae_sex']</td>"
display_string += "<td>row['ae_wpm']</td>"
display_string += "</tr>"
print "Query: ", query, "<br>"
display_string += "</table>"
print display_string

Categories