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()
# ...
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'
My Code:
From Python 3.8
def email_address_grab(email_list):
""" This function takes in a list of emails and puts them into a sql database"""
#import module
import sqlite3 as sql
#Setup sql
#create connection for sql
connection = sql.connect("emailList.db")
#create cursor
crsr = connection.cursor()
#create sql table
cmd = """CREATE TABLE emails (
email_handle TEXT,
email_domain VARCHAR(20));"""
crsr.execute(cmd)
#iterate through email list
index = 0
for email in email_list:
#split email with a delimiter of "#"
email_list[index] = email.split('#')
index += 1
#while loop to put all data into table
ct = 0
while ct <= (len(email_list) - 1):
for i in range(0, len(email_list)):
for j in range(0, len(email_list)):
email_address_1 = email_list[i]
email_address_2 = email_list[j]
cmd = f"""INSERT INTO emails (email_handle, email_domain) VALUES ({email_address_1}, {email_address_2});"""
crsr.execute(cmd)
ct += 1
#get the contents of the table
crsr.execute("SELECT * FROM emails;")
#store contents in a variable
email_address_list = crsr.fetchall()
#save changes to sql table
connection.commit()
#close connection
connection.close()
#return print statement for data
return print(email_address_list)
Error:
Traceback (most recent call last):
File "c:/Users/USER/Desktop/email grabber.py", line 79, in
email_address_grab(["testemail123#gmail.com"])
File "c:/Users/USER/Desktop/email grabber.py", line 58, in email_address_grab
crsr.execute(cmd)
sqlite3.OperationalError: no such column: 'testemail123', 'gmail.com'
Your issue is because this is your final command string:
"""INSERT INTO emails (email_handle, email_domain) VALUES (testemail123, gmail.com);"""
while what is a valid string is:
"""INSERT INTO emails (email_handle, email_domain) VALUES ("testemail123", "gmail.com");"""
So you should be using something like:
cmd = f"""INSERT INTO emails (email_handle, email_domain) VALUES ('{email_address_1}', '{email_address_2}');"""
Although, with sqlite3, you should be passing in parameters with the execute call. This is to help prevent sql injection attacks because the way that you are using formatted strings can result in catastrophic attacks.
You should pass parameters to sqlite3 instances like this:
cmd = """INSERT INTO emails (email_handle, email_domain) VALUES (?, ?);"""
crsr.execute(cmd, (email_address_1, email_address_2))
I am trying to create a command line tool that generates a random string(password) of a given length, stores it in a sql db, and can be queried by name. The password generation and storing of it's output by a given name works beautifully, but trying to select only the password element is giving me trouble. I was able to select all from the table but that returns the name and the password. I only want the password returned. I thought about just splicing the output or even using the linux cut command, but I'd rather just get it from the select statement. Is this possible? My current SELECT statement returns: operation parameter must be a str. When I try it without the call to (name) at the end of the SELECT statement like this: query_password = """SELECT * FROM password_table WHERE name = ?"""
I get this error:
File "passbox.py", line 44, in <module>
query_pswd_by_name(name)
File "passbox.py", line 39, in query_pswd_by_name
c.execute(query_password)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 0 supplied.
BTW I'm sure my query_pswd_by_name function is all wrong, I've been experimenting. When I just create a connection and SELECT statement outside of a function it does return the name and password.
Also note that I've disguised my database file's name with asterisks for the purpose of this post. I am using an actual working db file in practice.
Here is all the code I've written so far:
import secrets
import string
import sqlite3
#CREATE PASSWORD OF GIVEN LENGTH
def get_pass(length):
return "".join(secrets.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + string.punctuation) for x in range(length))
length = int(input("Enter the length of password: "))
password= get_pass(length)
print(password)
name = str(input("Enter name for password: "))
#CREATE DATABASE CONNECTION
conn = sqlite3.connect("****.db")
#CREATE CURSOR OBJECT
c = conn.cursor()
#CREATE TABLE IN DISK FILE BASED DATABASE
c.execute("""CREATE TABLE IF NOT EXISTS password_table (
name TEXT,
pswd TEXT
)""")
c.execute("INSERT INTO password_table (name, pswd) VALUES (?, ?)", (name, password))
#COMMIT CHANGES
conn.commit()
conn.close()
def query_pswd_by_name(name):
conn = sqlite3.connect('****.db')
c = conn.cursor()
query_password = """SELECT * FROM password_table WHERE name = ?""", (name)
c.execute(query_password)
result = c.fetchall()
for row in result:
print(row[1])
conn.commit()
query_pswd_by_name(name)
#CLOSE CONNECTION
conn.close()```
You need to break up the argument to the execute call.
c.execute(*query_password)
Or
c.execute("""SELECT * FROM password_table WHERE name = ?""", (name))
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 am using python 2.7 with pyqt4.10 and sqlite3 Db, trying to get the user input from QlineEdit to insert into sqlite3 table that is already created
Table structure
CREATE TABLE `categories` (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`category_name` TEXT NOT NULL UNIQUE
);
And am trying to refresh the list in a Qlistwidget with the new data after adding the input
Here is my full code :
def proc():
input_user = self.lineEdit.text()
conn = sqlite3.connect('storage/container.db')
conn.row_factory = lambda c, row: row[0]
c = conn.cursor()
c.execute("INSERT INTO categories (category_name) VALUES (?)", (input_user, ))
conn.commit()
conn = sqlite3.connect('storage/container.db')
conn.row_factory = lambda c, row: row[0]
c = conn.cursor()
c.execute("SELECT category_name FROM categories")
category_all = c.fetchall()
for items in category_all:
self.listWidget.addItem(items)
conn.close()
As you see i used input_user = self.lineEdit.text() to get the user input from the QlineEdit
The error is :
Traceback (most recent call last):
File "C:\python\townoftechwarehouse\add_category.py", line 63, in proc
c.execute("INSERT INTO categories (category_name) VALUES (?)", (input_user, ))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
Found out that the problem was that am using Arabic characters which is not readable for qslite3 so I have to use unicode, here is the edit:
Changed :
input_user = self.lineEdit.text()
To :
input_user1 = self.lineEdit.text()
input_user = unicode(input_user1)