Inserting values in MySQL table using Python - python

I have a Bank table in MySQL with the following schema:
`User_id` int(11) NOT NULL AUTO_INCREMENT,
`Amount` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`User_id`)
I am trying to take Amount as input and enter a record in the table using Python. I run the following code for the same:
print " enter the bank amount"
Amount = raw_input()
cursor.execute('''INSERT into Bank (Amount)
values (%d)''',
(Amount))
cursor.execute('commit')
But, it shows following error:
Traceback (most recent call last):
File "create_user.py", line 23, in <module>
(Amount))
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute
query = query % tuple([db.literal(item) for item in args])
TypeError: %d format: a number is required, not str

raw_input() returns a string:
If the prompt argument is present, it is written to standard output
without a trailing newline. The function then reads a line from input,
converts it to a string (stripping a trailing newline), and returns
that.
>>> test = raw_input()
1
>>> test
'1'
>>> type(test)
<type 'str'>
You need to cast it to int (according to the Amount column type):
amount = int(raw_input()) # TODO: handle exceptions?
cursor = db.cursor()
cursor.execute("""
INSERT INTO
Bank (Amount)
VALUES
(%d)
""", (amount, ))
db.commit()

Related

Python - 'sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.' when insert data into table using sqlite3 python

I tried to put data in to a table using variabels, as you can see down below in the code. When I'm running this piece of code I get the following error:
What I want the code to do is, get the data out of the parameters i'm giving in to the function insert_data. And then using the wildcard questionmark symbol. To get the option to use the variabels as data. Not quite sure if it's the most propper way of doing so. But it does work in other occations. I just don't get why it does not work in this piece of code.
Traceback (most recent call last):
File "{path}", line 65, in <module>
insert_data()
File "{path}", line 56, in insert_data
query ("INSERT INTO computers (name, os, mac_addr) VALUES "
File "{path}", line 8, in query
cursor.execute(query, args)
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
MY CODE
import cgi
import sqlite3
from os import path, environ
def query(query, *args):
db = sqlite3.connect(database)
cursor = db.cursor()
cursor.execute(query, args)
resultaat = cursor.fetchall()
db.commit()
db.close()
return resultaat
def database_create():
if path.isfile(database) != True:
query("CREATE TABLE 'computers' ('name' TEXT, 'os' TEXT, 'mac_addr' TEXT,"
"'create_date' timestamp DEFAULT current_timestamp)")
query("CREATE TABLE 'data' ('computer_id' integer, 'mem_usage' float,"
"'cpu_usage' float, 'total_size' float, 'used_size' float, 'free_size' float,"
"'create_date' timestamp DEFAULT current_timestamp)")
query("CREATE TABLE 'grafieken' ('name' TEXT, 'legend' TEXT)")
query("CREATE TABLE 'gebruikers'('u_name' TEXT, 'p_word' TEXT)")
query("INSERT INTO 'gebruikers' (u_name, p_word) VALUES ('beheerder',"
"'695badbd075fdacd8638a600712f9aec74dd85b6ae61f7ab7f0f45e438196bf0aac117102d328e3d4e92fd5fc78f593a50875f900a7fe59f5d463bbf35af245c3b605ec3b6f91cbec7452801ca5ca95ebf00b248e73d07b9934d25ab21b6943a83d1944450854ef05044be01ff0d3b72b158209a70a28c3e063ec6a7f806d610')")
query("INSERT INTO grafieken VALUES ('Totale hardeschijf ruimte', 'Ruimte (GB), hoger is beter')")
query("INSERT INTO grafieken VALUES ('Beschikbare hardeschijf ruimte', 'Ruimte (GB), hoger is beter')")
query("INSERT INTO grafieken VALUES ('Gebruikte hardeschijf ruimte', 'Ruimte (GB), lager is beter')")
query("INSERT INTO grafieken VALUES ('Geheugenverbruik', 'Geheugen (%), lager is beter')")
query("INSERT INTO grafieken VALUES ('CPU-verbruik', 'Processor (%), lager is beter')")
print ('done')
elif path.isfile(database) == True:
print ('DB already exists')
else:
print('failed')
def insert_data():
try:
import psutil
except ImportError:
print('no psutil installed')
exit(1)
import platform
import uuid
diskspace = psutil.disk_usage('/')
spacetoGB = [diskspace[0] // (2 ** 30), diskspace[1] // (2 ** 30), diskspace[2] // (2 ** 30)] # Total, used, free
name = platform.uname()[1],
mac_addr = '%012x' % uuid.getnode(), # https://stackoverflow.com/questions/13864608/get-mac-address-in-python-and-append-to-string
#totalsize = spacetoGB[0],
#usedsize = spacetoGB[1],
#freesize = spacetoGB[2],
os = platform.system() + " " + platform.release(),
# memusage = psutil.virtual_memory().percent,
# cpu_usage = psutil.cpu_percent(interval=1)
query ("INSERT INTO computers (name, os, mac_addr) VALUES "
"(?,?,?)", *(name, os, mac_addr,))
data = 'Record added'
print (data)
#return data
database = "tester.db"
database_create()
insert_data()
The commas (,) terminating the set statments (eg name = platform.uname()[1],) cast the variables as tuples.

Cannot to insert record into table Incorrect number of bindings supplied

Cannot to insert into ShopifyMonitor table record (there 2 field: id, name)
full traceback of error:
File "D:\Related To Python (Tutorials)\Python-Test\Working With Database\goo.py", line 174, in <module>
c.execute(make_shopify_name, (shopify_name))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 10 supplied.
.
get_site = str(input('Enter site here: '))
url = fix_url(get_site)
shopify_name = fix_url(get_site, True)
basepath = os.path.dirname(__file__)
db_name = '{}/shopify.sqlite3'.format(basepath)
sql_create_projects_table = """ CREATE TABLE IF NOT EXISTS ShopifyMonitor (
id integer PRIMARY KEY AUTOINCREMENT,
name text UNIQUE NOT NULL
);"""
sql_create_tasks_table = """ CREATE TABLE IF NOT EXISTS Product (
id integer PRIMARY KEY AUTOINCREMENT,
product_id text NOT NULL,
updated_at text NOT NULL,
title text NOT NULL,
link_to_product text UNIQUE NOT NULL,
vendor text NOT NULL,
sku text NOT NULL,
quantity text NOT NULL,
options text,
price text NOT NULL,
collection_id text,
collection_updated text,
shopify_name text NOT NULL,
FOREIGN KEY(shopify_name) REFERENCES ShopifyMonitor(name)
);"""
make_shopify_name = '''INSERT INTO ShopifyMonitor(name) VALUES (?) '''
conn = create_connection(db_name)
if conn is not None:
# create projects table
create_table(conn, sql_create_projects_table)
# create tasks table
create_table(conn, sql_create_tasks_table)
else:
print("Error! cannot create the database connection.")
c = conn.cursor()
c.execute(make_shopify_name, (shopify_name))
conn.commit()
It looks like your post is mostly code; please add some more details.add some more details.
The issue is subtle:
c.execute(make_shopify_name, (shopify_name))
Should be:
c.execute(make_shopify_name, (shopify_name,)) # note comma after shopify_name
The second parameter passed into execute should be a tuple of parameters for the query - even if there's only one parameter, it still has to be a tuple.
At the moment all you have is parentheses around a variable name - the parentheses will basically be ignored by Python as they don't mean anything.
It's a common misconception that it's the parentheses that make a tuple - it's not, it's the comma:
x = (1) # x is 1
x = 1, # x is a tuple containing a single value, the integer 1
x = (1,) # as above - but the parentheses aren't actually required syntactically here

Python Postgres Insert into error

Hello all I have to make a bulk entry to my postgresql table from python for loop code. I have tried all possible means to enter the data. But I was unable to to do it.
data = count,ipaddress,asn_value,asno,aso,sock_value,sock,datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
print (data)
cur.execute('insert into dataoldnew values (%s,%s,%s,%s,%s,%s,%s,%s)',data)
print("Records created successfully")
conn.close()
Debug
data= (1, '217.76.156.252', 1, 8560, '1&1 Internet SE', 0, 0, '2018-06-06 11:35')
Error
Exception in callback task2() at mining.py:43
handle: <Handle task2() at mining.py:43>
Traceback (most recent call last):
File "/usr/lib/python3.5/asyncio/events.py", line 125, in _run
self._callback(*self._args)
File "mining.py", line 31, in wrapper
ret = func(*args, **kwargs)
File "mining.py", line 149, in task2
cur.execute('insert into dataoldnew values (%s,%s,%s,%s,%s,%s,%s,%s)',data)
psycopg2.DataError: invalid input syntax for integer: "217.76.156.252"
LINE 1: insert into dataoldnew values (1,'217.76.156.252',1,8560,'1&...
^
I have a table in postgresql.
Postgres Table Schema
-- Table: public.dataoldnew
-- DROP TABLE public.dataoldnew;
CREATE TABLE public.dataoldnew
(
index bigint,
idtemp bigint,
ipaddress text,
"timestamp" text,
values_asn bigint,
values_aso text,
values_host_name text,
values_host_name_true_false bigint
)
WITH (
OIDS=FALSE
);
ALTER TABLE public.dataoldnew
OWNER TO aditya;
-- Index: public.ix_dataoldnew_index
-- DROP INDEX public.ix_dataoldnew_index;
CREATE INDEX ix_dataoldnew_index
ON public.dataoldnew
USING btree
(index);
Thanks Advance

TypeError: 'str' object is not callable (mysql-python)

I am coding with mysql-python.
To add a new record into database, I use the following piece of code:
# Open database connection
db = MySQLdb.connect("localhost","root","admin","majoranalysis" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "INSERT INTO
# insert a record
jobdetail(title,date_accessed,description,requirement,url) \
VALUES(%(title)s,%(data_accessed)s,%(description)s,%(requirement)s,%(url)s)"
dt = ('data analysist',date(2015,4,16),'description','requirement',joblistlink[0])
cursor.execute(sql,dt)
The problem is not to declare str, but the error occurs likely:
Traceback (most recent call last):
File "./re-ex.py", line 81, in <module>
dt = ('data analysist',date(2015,4,16),'description','requirement',joblistlink[0])
TypeError: 'str' object is not callable
The sql command to create the table is:
CREATE TABLE IF NOT EXISTS `jobdetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
`date_accessed` date NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL,
`requirement` text COLLATE utf8_unicode_ci NOT NULL,
`url` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
Do you know where is the bug?
Because you use the %(key)s as a place holder in your sql str.So that means you should use a dictionary to give the data to the sql.
Eg.
give tuple to %s like :print "%s:%s" % ('key', 'val')
give dict to %(key)s like print '%(k1)s:%(v1)s' % {'k1':'key', 'v1':'val'}
In case you still dont know how to fix your problem.Change to
dt={'title':'data analysist',
'data_accessed':date(2015,4,16),
'description':'description',
'requirement':'requirement',
'url':joblistlink[0]}

python MySQLdb got invalid syntax when trying to INSERT INTO table

## COMMENT OUT below just for reference
""
cursor.execute ("""
CREATE TABLE yellowpages
(
business_id BIGINT(20) NOT NULL AUTO_INCREMENT,
categories_name VARCHAR(255),
business_name VARCHAR(500) NOT NULL,
business_address1 VARCHAR(500),
business_city VARCHAR(255),
business_state VARCHAR(255),
business_zipcode VARCHAR(255),
phone_number1 VARCHAR(255),
website1 VARCHAR(1000),
website2 VARCHAR(1000),
created_date datetime,
modified_date datetime,
PRIMARY KEY(business_id)
)
""")
""
## TOP COMMENT OUT (just for reference)
## code
website1g = "http://www.triman.com"
business_nameg = "Triman Sales Inc"
business_address1g = "510 E Airline Way"
business_cityg = "Gardena"
business_stateg = "CA"
business_zipcodeg = "90248"
phone_number1g = "(310) 323-5410"
phone_number2g = ""
website2g = ""
cursor.execute ("""
INSERT INTO yellowpages(categories_name, business_name, business_address1, business_city, business_state, business_zipcode, phone_number1, website1, website2)
VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s')
""", (''gas-stations'', business_nameg, business_address1g, business_cityg, business_stateg, business_zipcodeg, phone_number1g, website1g, website2g))
cursor.close()
conn.close()
I keep getting this error
File "testdb.py", line 51
""", (''gas-stations'', business_nameg, business_address1g, business_cityg, business_stateg, business_zipcodeg, phone_number1g, website1g, website2g))
^
SyntaxError: invalid syntax
any idea why?
Thanks for the help in advance
Update #2, I have removed the double single quote on the "categories_name", but now even
import MySQLdb
conn = MySQLdb.connect(host="localhost",port=22008,user="cholestoff",passwd="whoami",db="mydatabase")
cursor = conn.cursor()
## Find mysql version
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone()
print "server version:", row[0]
website1g = "http://www.triman.com"
business_nameg = "Triman Sales Inc"
business_address1g = "510 E Airline Way"
business_cityg = "Gardena"
business_stateg = "CA"
business_zipcodeg = "90248"
phone_number1g = "(310) 323-5410"
phone_number2g = ""
cursor.execute ("""
INSERT INTO yellowpages(categories_name, business_name)
VALUES ('%s','%s')
""", ('gas-stations', business_nameg))
cursor.close()
conn.close()
still gotten this error
server version: 5.1.33-community
Traceback (most recent call last):
File "testdb.py", line 23, in <module>
""", ('gas-stations', business_nameg))
File "C:\Python26\lib\site-packages\MySQLdb\cursors.py", line 173, in execute
self.errorhandler(self, exc, value)
File "C:\Python26\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use
near 'gas-stations'',''Triman Sales Inc'')' at line 2")
Thanks again for the help
I think your problem is here:
''gas-stations''
This gives a syntax error. You probably want to use one set of quotes:
'gas-stations'
If you want to insert the value 'gas-stations' into the database including the quotes then you can either escape the quotes or surround the string with double-quotes instead of single quotes:
"'gas-stations'"
The reason why the "up arrow" is pointing at the wrong place is because your lines are so long that it is wrapping on your console. Make your lines shorter, or widen your console window to see where the error really is.
For your second problem, you need to lose all those single-quote characters in your VALUES clause ... should look like VALUES (%s,%s) not like VALUES ('%s','%s').
The general rules are very simple: for each parameter, have one place-marker (in the case of mySQLdb this is %s) in your SQL statement, and supply one Python expression in your tuple of parameters. Then lean back and let the interface software do the right thing for you. This includes quoting strings properly. Don't try to do it your self. In particular, string expressions should be exactly what you expect to retrieve later.
Example: The business_name of a gas station is "O'Reilly's Pump'n'Go" as a Python string constant. This will end up in the constructed SQL as ...VALUES(...,'O''Reilly''s Pump''n''Go',... without you having to think about it.
You can't use doubled single-quotes (i.e. ''gas-stations'') - use either just single single-quotes ('gas-stations'), or actual double quotes ("gas-stations").
I also got such error and I solved it by replacing '%s' by %s under values.
VALUES(%s,%s)

Categories