import cursor as cursor
import requests
import pprint
import pyodbc
:
conn = pyodbc.connect('Driver={SQL Server};'
'Server=MY-PC-PC;'
'Database=test;'
'Trusted_Connection=yes;')
def read(conn):
print("Read")
cursor = conn.cursor()
cursor.execute('select * FROM test.dbo.books')
for row in cursor:
print(f'row = {row}')
print()
r = requests.get('https://5f97076911ab98001603b6d0.mockapi.io/api/v1/books')
# pprint.pprint(r.json()) #to print all the data
# pprint.pprint(r.json()[1]['author']) #to print user number 2 data
print(r.json()[1]['author'])
cursor = conn.cursor()
for i in range(50):
cursor.execute("INSERT INTO dbo.books (id, createdAt, title, author, imageUrl) "
"VALUES (r.json[i] ,r.json()[i]['createdAt'],r.json()[i]['title'], r.json()[i]['author'],r.json()[i]['imageUrl'] )")
conn.commit();
read(conn);
read(conn)
cursor.close()
I keep getting this error:
Traceback (most recent call last):
File "C:/Users/MY-PC/PycharmProjects/pythonProject2/py.py", line 40, in
cursor.execute("INSERT INTO dbo.books (id, createdAt, title, author, imageUrl) "
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'i'. (102) (SQLExecDirectW)")
Process finished with exit code 1
You are not using "i" or "r" as variables there, but as simple text. Try using a fstring, which would be putting an f before the "" and using {} to use your variables, as I do in this example:
name = "MyName"
print(f"Hello {name}")
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 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 encountered error message (INVALID SYNTAX) and have no idea why it happens.
Please help to figure it out.
import pymysql
db = pymysql.connect(host='localhost', port=3306, user='root', passwd='xxxxxxxx', db='ecommerce', charset='utf8')
ecommerce = db.cursor()
for index in range(10):
product_code = 215673140 + index +1
sql=INSERT INTO product VALUES(str(product_code),'sample data1','sample date2','sample data3'); ----> here's error point.
ecommerce.execute(sql)
db.commit()
db.close()
Try this. You have to enclose INSERT INTO ... inside " ". Also, don't use ; after the statement.
I suggest you should use %s. That way, you can insert any value inside that column
import pymysql
db = pymysql.connect(host='localhost', port=3306, user='root', passwd='xxxxxxxx', db='ecommerce', charset='utf8')
ecommerce = db.cursor()
for index in range(10):
product_code = 215673140 + index +1
sql = "INSERT INTO product VALUES (%s, %s,%s,%s,%s)"
val = (str(product_code),'sample data1','sample date2','sample data3')
ecommerce.execute(sql, val)
db.commit()
db.close()
So I am trying to create an auto update to SQL from another excel file, by unique value, as to know what is the new data to add to the database..
There's different in columns names between the database and the excel file as in the database and names without spaces...
I tried to do it with pandas it gave me the same error
So here's my simple code tried with xlrd
import xlrd
from sqlalchemy import create_engine
def insert():
book = xlrd.open_workbook(r"MNM_Rotterdam_5_Daily_Details-20191216081027 - Copy (2).xlsx")
sheet = book.sheet_by_name("GSM Details")
database = create_engine(
'mssql+pyodbc://WWX542337CDCD\SMARTRNO_EXPRESS/myDB?driver=SQL+Server+Native+Client+11.0') # name of database
cnxn = database.raw_connection
cursor = cnxn.cursor()
query = """Insert INTO [myDB].[dbo].[mnm_rotterdam_5_daily_details-20191216081027] (Date, SiteName, CellCI, CellLAC, CellName, CellIndex) values (?,?,?,?,?,?)"""
for r in range(1, sheet.nrows):
date = sheet.cell(r,0).value
site_name = sheet.cell(r,3).value
cell_ci = sheet.cell(r,4).value
cell_lac = sheet.cell(r,5).value
cell_name = sheet.cell(r,6).value
cell_index = sheet.cell(r,7).value
values = (date, site_name, cell_ci, cell_lac, cell_name, cell_index)
cursor.execute(query, values)
cnxn.commit()
# Close the cursor
cursor.close()
# Commit the transaction
database.commit()
# Close the database connection
database.close()
# Print results
print ("")
print ("")
columns = str(sheet.ncols)
rows = str(sheet.nrows)
print ("Imported", columns,"columns and", rows, "rows. All Done!")
insert()
and this is the error:
I tried to change the range I found another error:
Traceback (most recent call last):
File "D:/Tooling/20200207/uniquebcon.py", line 48, in <module>
insert()
File "D:/Tooling/20200207/uniquebcon.py", line 37, in insert
database.commit()
AttributeError: 'Engine' object has no attribute 'commit'
I think this is related to SQL-Alchemy in the connection
Instead of creating the cursor directly with
cursor = database.raw_connection().cursor()
you can create a connection object, then create the cursor from that, and then call .commit() on the connection:
cnxn = database.raw_connection()
crsr = cnxn.cursor()
# do stuff with crsr ...
cnxn.commit()
I tried performing a search query from the backend of an app I'm working and I got the response below:
Traceback (most recent call last):
File "backend.py", line 30, in search
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", self.NmRqst.text)
ValueError: parameters are of unsupported type
I have the code below:
def connectfile(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS PlanInfo (Plan Number TEXT, Tracing Number TEXT, Submitted By TEXT, "
"Location TEXT)")
conn.commit()
conn.close()
def search(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", self.NmRqst.text)
rows = cur.fetchall()
conn.close()
return rows
self.NmRqst.text is the QLineEdit that accepts the user input for database query...
Feel free to correct the question as you deem fit!
I have edited the lines of code,
def connectfile(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS PlanInfo (Plan_Number TEXT, Tracing_Number TEXT, Submitted_by TEXT, "
"Location TEXT)")
conn.commit()
conn.close()
def search(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", str(self.NmRqst.text,))
rows = cur.fetchall()
conn.close()
return rows
...and I got the following error:
Traceback (most recent call last):
File "backend.py", line 30, in search
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", str(self.NmRqst.text,))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 64 supplied.