The assert statement in the following code fails in an environment running mariadb, while it runs fine in an (older) environment running mysql. The mariadb environment seems to not persist the result of the insert statement. Connecting with a command line client confirms that the insert was not persisted.
import MySQLdb
def newCon():
return MySQLdb.connect('localhost', 'root', '', 'test')
def testStatement(con, aStatement):
# print "---"
# print aStatement
cur = con.cursor()
cur.execute(aStatement)
result = cur.fetchall()
cur.close()
# print result
return result
def test():
con = newCon()
testStatement(con, "DROP TABLE IF EXISTS TestTable")
testStatement(con, """CREATE TABLE TestTable (
id INT NOT NULL AUTO_INCREMENT,
AccountId VARCHAR(50),
PRIMARY KEY(id))""")
testStatement(con, "INSERT INTO TestTable (AccountId) VALUES ('XYZ')")
myCount1 = testStatement(con, "SELECT count(*) from TestTable")[0][0]
con.close()
con = newCon()
myCount2 = testStatement(con, "SELECT count(*) from TestTable")[0][0]
con.close()
assert myCount1 == myCount2, \
"count1 = " + str(myCount1) + " != count2 = " + str(myCount2)
test()
The environment in which it runs fine is:
CentOS 6.7
python 2.6.6
mysql-python 1.2.3
mysql server 5.1.73
The environment in which it fails is:
Fedora 21
python 2.7.8
mysql-python 1.2.3
mariadb server 10.0.21
The failed output reads:
Test2.py:10: Warning: Table 'mysql.table_stats' doesn't exist
cur.execute(aStatement)
Traceback (most recent call last):
File "Test2.py", line 37, in <module>
test()
File "Test2.py", line 35, in test
"count1 = " + str(myCount1) + " != count2 = " + str(myCount2)
AssertionError: count1 = 1 != count2 = 0
I don't know what the table_stats warning is about.
Question: Am I using the api correctly? Can anybody make this test pass with a mariadb environment?
You haven't committed the transaction.
Related
# Create the connection object
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "umar1234",
database="date_sheet"
)
# print(mydb)
# # To Create Database
mycursor = mydb.cursor()
# creating column list for insertion#BSIT(M)-VII
print(data.columns.tolist())
cols = "`,`".join([str(i) for i in data])
for i,row in data.iterrows():
sql = "INSERT INTO `room` (`" +cols + "`) VALUES (" + "%s,"*(len(row)-1) + "%s)"
# cursor.execute(sql, tuple(row))
cursor.execute()
connection.commit()
i want to insert data frame into sql workbench ...
database name ,and username and password is mentioned..
but i got an error..
Traceback (most recent call last):
File "C:\Users\UMAR\PycharmProjects\FYP\scend.py", line 36, in <module>
cursor.execute()
AttributeError: module 'mysql.connector.cursor' has no attribute 'execute'
I am trying to run some SQL statements in a Python environment in Visual Studio Code. The database that I am querying is in MySQL Workbench 8.0. My program runs smoothly until it reaches the querying part. It connects to the database fine. Here is my code:
from gettext import install
import pymysql
con = pymysql.Connect( #Creating connection
host = 'localhost', #
port = 3306, #
user = 'root', #
password = 'Musa2014', #
db = 'referees', #
charset = 'utf8' #
)
Ref_Info = input("Enter referee details: ") #First input statement
Ref_First_Name, Ref_Last_Name, Ref_Level = Ref_Info.split()
Ref_Info_Table = []
RefID = 1 #Setting the value of the RefID
while Ref_Info != '': #Creating loop to get referee information
Ref_Info = Ref_Info.split()
Ref_Info.insert(0, int(RefID))
Ref_Info_Table.append(Ref_Info) #Updating Ref_Info_Table with new referee data
print(Ref_Info_Table) #Printing values #
print(Ref_Info) #
print('Referee ID:', RefID) #
print('Referee First Name:', Ref_First_Name) #
print('Referee Last Name:', Ref_Last_Name) #
print('Referee Level:', Ref_Level) #
Ref_First_Name = Ref_Info[1]
Ref_Last_Name = Ref_Info[2]
Ref_Level = Ref_Info[3]
RefID = RefID + 1 #Increasing the value of RefID
Ref_Info = input("Enter referee details: ") #Establishing recurring input again
cur = con.cursor()
sql_query1 = 'INSERT INTO ref_info VALUES(1, MuhammadMahd, Ansari, B&W)'
sql_query2 = 'SELECT * FROM ref_info'
cur.execute(sql_query1)
cur.execute(sql_query2)
data = cur.fetchall()
con.commit()
cur.close()
con.close()
This is the error that I recieved:
Exception has occurred: OperationalError
(1054, "Unknown column 'MuhammadMahd' in 'field list'")
File "C:\Users\mahd_.vscode\Code Folders\Testing\test2.py", line 44, in
cur.execute(sql_query1)
It would be helpful if you could explain the error and tell me how to resolve it.
Thank you.
The statement in sql_query1
sql_query1 = 'INSERT INTO ref_info VALUES(1, MuhammadMahd, Ansari, B&W)'
miss the " quoting character for string literal; this statement would be sent to your mysql server as
INSERT INTO ref_info VALUES(1, MuhammadMahd, Ansari, B&W)
in which MuhammadMahd and Ansari and B&W do not refer to any column or expression, and are not string literals either. You have to add " to make them string literals:
sql_query1 = 'INSERT INTO ref_info VALUES(1, "MuhammadMahd", "Ansari", "B&W")'
And, to not have to deal to special character escape, you could use python's """ to start and end a string, which is better when you are writing sql in python:
sql_query1 = """INSERT INTO ref_info VALUES(1, "MuhammadMahd", "Ansari", "B&W")"""
I have made this python method:
def move_player_list_item(start_position,end_position,player_list_item):
conn = create_connection()
query = "DELETE FROM `player_list` WHERE `position`=?;"
cur = conn.cursor()
cur.execute(query,(str(start_position),))
conn.commit()
if start_position<end_position:
query = "UPDATE `player_list` SET `position`=`position`-1 WHERE `position`>? AND `position`<=?;"
cur = conn.cursor()
cur.execute(query,(str(start_position),str(end_position)))
conn.commit()
elif end_position<start_position:
query = "UPDATE `player_list` SET `position`=`position`+1 WHERE `position`>=? AND `position`<?;"
cur = conn.cursor()
cur.execute(query,(str(end_position),str(start_position)))
conn.commit()
query = query = "INSERT INTO `player_list` (`play`, `relative_type`, `relative_number`, `repeats`, `duration_milliseconds`, `duration_human`,`position`) VALUES (?,?,?,?,?,?,?)"
cur = conn.cursor()
cur.execute(query,(str(player_list_item["play"]),str(player_list_item["relative_type"]),str(player_list_item["relative_number"]),str(int(player_list_item["repeats"])),str(int(player_list_item["duration_milliseconds"])),str(player_list_item["duration_human"]),str(end_position)))
conn.commit()
return 1
When start_position<end_position works with no error.
But when end_position<start_position there is an error:
Traceback (most recent call last):
File "C:\Users\Χρήστος Παππάς\Έγγραφα\projects\Papinhio player\Αρχεία βάσης δεδομένων (Sqlite3)\Έλεγχος συναρτήσεων sqlite3 (check sqlite3 functions).py", line 977, in <module>
main()
File "C:\Users\Χρήστος Παππάς\Έγγραφα\projects\Papinhio player\Αρχεία βάσης δεδομένων (Sqlite3)\Έλεγχος συναρτήσεων sqlite3 (check sqlite3 functions).py", line 925, in main
sqlite3_functions.move_player_list_item(30,20,player_list_items_db[29])
File "C:/Users/Χρήστος Παππάς/Έγγραφα/projects/Papinhio player/Αρχεία βάσης δεδομένων (Sqlite3)/../Αρχεία πηγαίου κώδικα εφαρμογής (Python)/Αρχεία κώδικα python (Python files)/Συναρτήσεις sqlite3 (Sqlite3 functions).py", line 1125, in move_player_list_item
cur.execute(query,(str(end_position),str(start_position)))
sqlite3.IntegrityError: UNIQUE constraint failed: player_list.position
The only solution i have thought about is to remove the unique constraint.
Is there any better solution?
I'm new to using sqlite3 with python. I'm having trouble with making the insert_row function in my database class. From the manual on the execute function it appears that I'm doing everything correctly https://docs.python.org/2/library/sqlite3.html. This function does return a number which appears to be correct for lastrowid. However, when I access sqlite3 via command line the table is empty.
def insert_row(self, table, input_dict):
'''
(str, dict) -> int
Add a row to a table in the database
'''
count = 0
col_names = input_dict.keys()
insert_sql = 'INSERT INTO ' + self.sanitize(table) + ' (' + utils.list_to_char_seperated(col_names, ', ', False) + ') VALUES ('
for col in col_names:
count += 1
insert_sql += "'" + self.sanitize(input_dict[col]) + "'"
if count < len(col_names):
insert_sql += ', '
else:
insert_sql += ');'
cur = self.conn.cursor()
cur.execute(insert_sql)
return cur.lastrowid
Accessing via command line.
$ sqlite3
SQLite version 3.11.0 2016-02-15 17:29:24
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open blood_cultures.db
sqlite> .tables
vein_draws
sqlite> SELECT * FROM vein_draws;
sqlite>
Also if I take the result of the insert_sql variable and insert it directly into the database via a command line connection this works. So I do not believe it is my insert statement.
Any ideas on what I am doing wrong here?
I'm trying to move data in the same row from one field to another.
This is my code, but it doesn't work with the update statement:
def update_ondemanddrama(Name):
with sqlite3.connect("sky_ondemand.db") as db:
cursor = db.cursor()
sql = "update TVshowsDrama set SecLastEp=LastEp where Name=?"
cursor.execute(sql, Name)
db.commit()
works
def insert_ondemanddrama(values):
with sqlite3.connect("sky_ondemand.db") as db:
cursor = db.cursor()
sql = "update TVshowsDrama set Name=?, LastEp=? where Name=?"
cursor.execute(sql,values)
db.commit()
def insert_ondemanddoc(values):
with sqlite3.connect("sky_ondemand.db") as db:
cursor = db.cursor()
sql = "update TVshowsDoc set Name=?, LastEp=? where Name=?"
cursor.execute(sql,values)
db.commit()
Type = int(input("Doc (1) or Drama (2)"))
Name = input("Enter name of Show")
LastEp = input("Enter Last episode aired (ex. s1e4)")
if Type == 1:
if __name__== "__main__":
show = (Name, LastEp, Name)
insert_ondemanddoc(show)
elif Type == 2:
if __name__== "__main__":
show = (Name, LastEp, Name)
update_ondemanddrama(Name)
insert_ondemanddrama(show)
elif Type >=3:
print ("Incorrect entry")
The error I get running this in python is:
Traceback (most recent call last): File "C:\Users\ict\Downloads\skyondemandv1.py", line 65, in <module>
update_ondemanddrama(Name) File "C:\Users\ict\Downloads\skyondemandv1.py", line 34, in
update_ondemanddrama cursor.execute(sql, Name) sqlite3.ProgrammingError: Incorrect number of bindings supplied.
The current statement uses 1, and there are 5 supplied.
cursor.execute expects an iterable. When you give it a string, execute perceives it as a 5 item iterable (5 characters).
Change the execute line to
cursor.execute(sql, (Name,))