how to insert dataframe into sql workbench. on local host - python

# 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'

Related

How to pass a variable as a column name with pyodbc?

I have a list that has two phone numbers and I'd like to put each phone number into its own column in an Access database. The column names are Phone_Number1 and Phone_Number2. How do I pass that to the INSERT statement?
phone_numbers = ['###.218.####', '###.746.####']
driver = '{Microsoft Access Driver (*.mdb, *.accdb)}'
filepath = 'C:/Users/Notebook/Documents/master.accdb'
myDataSources = pyodbc.dataSources()
access_driver = myDataSources['MS Access Database']
conn = pyodbc.connect(driver=driver, dbq=filepath)
cursor = conn.cursor()
phone_number_count = 1
for phone_number in phone_numbers:
column_name = "Phone_Number" + str(phone_number_count)
cursor.execute("INSERT INTO Business_Cards (column_name) VALUES (?)", (phone_number))
conn.commit()
print("Your database has been updated.")
This is what I have so far.
Traceback (most recent call last):
File "C:/Users/Notebook/PycharmProjects/Jarvis/BusinessCard.py", line 55, in <module>
database_entry(phone_numbers, emails, name, title)
File "C:/Users/Notebook/PycharmProjects/Jarvis/BusinessCard.py", line 47, in database_entry
cursor.execute("INSERT INTO Business_Cards (column_name) VALUES (?)", (phone_number))
pyodbc.Error: ('HYS22', "[HYS22] [Microsoft][ODBC Microsoft Access Driver] The INSERT INTO statement contains the following unknown field name: 'column_name'. Make sure you have typed the name correctly, and try the operation again. (-1507) (SQLExecDirectW)")
If you want to insert both numbers in the same row, remove the for loop and adjust the INSERT to consider the two columns:
phone_numbers = ['###.218.####', '###.746.####']
# ...
column_names = [f"PhoneNumber{i}" for i in range(1, len(phone_numbers) + 1)]
placeholders = ['?'] * len(phone_numbers)
cursor.execute(f"INSERT INTO Business_Cards ({', '.join(column_names)}) VALUES ({', '.join(placeholders)})", tuple(phone_numbers))
conn.commit()
# ...

Sqlite3 Change position column (reordering)

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?

Inserting json data into a SQL Server table

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}")

how to connect mysql database in python using pymysql,KEY ERROR

im pretty new with python,im sorry if my question and my english doesnt sound right at all.
ive been trying to integrated my scraping output to mysql,but unfortunately i got stuck.can you good people help me?
the output/error
*<pymysql.cursors.Cursor object at 0x000000E81FF095E0>
<pymysql.connections.Connection object at 0x000000E81FEF9070>
KeyError Traceback (most recent call last)
in
9 data = csv.DictReader(scrapeddata)
10 for row in data:
---> 11 sql = "INSERT INTO emas ( tanggal, terakhir, pembukaan, tertinggi, terendah, vol, perubahan%) VALUES ('%s','%s','%s','%s','%s','%s','%s')" %(str(row["tanggal"]),str(row["terakhir"]),str(row["pembukaan"]),str(row["tertinggi"]),str(row["terendah"]),str(row["vol"]),str(row["perubahan%"]))
12 print(sql)
13 cur.execute(sql)
KeyError: 'tanggal'*
this is my code
import csv
import pymysql
#Connecting to MySQL in Windows
conn = pymysql.connect(host="127.0.0.1", port = 3306, user = "root", passwd = '', database = "mysql",
charset = "utf8")
cur = conn.cursor()
cur.execute("USE historis")
print(cur)
print(conn)
with open(r'C:\Users\shulhan\output_emas.csv') as scrapeddata:
data = csv.DictReader(scrapeddata)
for row in data:
sql = "INSERT INTO emas ( tanggal, terakhir, pembukaan, tertinggi, terendah, vol, perubahan%)
VALUES ('%s','%s','%s','%s','%s','%s','%s')"
%(str(row["tanggal"]),str(row["terakhir"]),str(row["pembukaan"]),str(row["tertinggi"]),str(row["terendah"]),str(row["vol"]),str(row["perubahan%"]))
print(sql)
cur.execute(sql)
conn.commit()
i think your connection setup should look like this:
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
you can find more information here:
https://pymysql.readthedocs.io/en/latest/user/examples.html

AttributeError: 'Engine' object has no attribute 'conn'

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()

Categories

Resources