Can't insert variable values into mysql database by using python - python

Recently,I've got a project that I need to save variable values into a database.
I want to program a code like this:
If I want to input username="Jonh", gender="Male", age=23, password="123456789", id="11111111"
then the code looks like:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
import sys
db = MySQLdb.connect("140.120.31.124","usr1","606","testdb",port=3306 )
cursor = db.cursor()
urn="Jonh"
gdr="male"
agex="23"
psd="123456789"
idx="11111111"
sql = """INSERT INTO table1(username,gender,age,password,id) VALUES(%s,%s,%s,%s,%s)""" %(urn,gdr,agex,psd,idx)
#sql="""INSERT INTO table1(username,gender,age,password,id) VALUES("Jonh","male","23","123456789","11111111")"""
try:
cursor.execute(sql)
db.commit()
except Exception as inst:
db.rollback()
print inst
db.close()
The structure of database I set is:
username varchar(50) utf8_unicode_ci
gender varchar(50) utf8_unicode_ci
age int(2)
password varchar(20) utf8_unicode_ci
id varchar(8) utf8_unicode_ci
But, it always shows the error --> (1054, "Unknown column 'Jonh' in 'field list'")
Does anyone can help me to solve this problem? Thanks a lot.
PS. The code I refer is https://www.packtpub.com/mapt/book/big_data_and_business_intelligence/9781849510189/3/ch03lvl1sec24/using-user-defined-variables

You must not use string substitution. Use parameters.
sql = """INSERT INTO table1(username,gender,age,password,id) VALUES(%s,%s,%s,%s,%s)"""
cursor.execute(sql, (urn,gdr,agex,psd,idx))
That book appears to be recommending unsafe practices. You should stop reading it immediately.

Related

insert from CSV file to PostgreSQL table with integer values type

I want to insert data from a CSV file into a PostgreSQL table. The table
structure is given below. But I am unable to give input of INTEGER type values.
It is showing error like-
DataError: invalid input syntax for integer: "vendor_phone"
LINE 1: ...vendor_phone,vendor_address)VALUES ('vendor_name','vendor_ph...
It is working fine if I use VARCHAR type. But i need to use integer values.
CREATE TABLE vendors (
vendor_id SERIAL PRIMARY KEY,
vendor_name VARCHAR(100) NOT NULL,
vendor_phone INTEGER,
vendor_address VARCHAR(255) NOT NULL
)
import psycopg2
import csv
database = psycopg2.connect (database = "supplier", user="postgres", password="1234", host="localhost", port="5432")
cursor = database.cursor()
vendor_data = csv.reader(open('vendors.csv'),delimiter=',')
for row in vendor_data:
cursor.execute("INSERT INTO vendors (vendor_name,vendor_phone,vendor_address)"\
"VALUES (%s,%s,%s)",
row)
print("CSV data imported")
cursor.close()
database.commit()
database.close()
instead of cursor, you can use below statement to load data directly from CSV to table which skips Header of the CSV file
COPY vendors (vendor_name,vendor_phone,vendor_address) FROM 'vendors.csv' CSV HEADER;

Not able to insert into mysql database

I have just started using MySQLdb in python. I am able to create table but when I try to insert, no rows are inserted into the table and its shows that table is still empty.
import MySQLdb
db = MySQLdb.connect("localhost","root","shivam","test")
cursor = db.cursor()
s = "DROP TABLE IF EXISTS batting"
cursor.execute(s)
s = """create table batting (
name varchar(50) primary key,
matches integer(5),
innings integer(5),
runs integer(5),
highest integer(3),
strikerate integer(3),
hundreds integer(3),
fifties integer(3)
)"""
cursor.execute(s)
s = """insert into batting(name) values(
"shivam")"""
cursor.execute(s)
db.close()
Where I could be going wrong?
You forgot to commit your connection. Simply add:
cursor.execute(s)
db.commit()
Have a look at this. It explains why you need to commit

How to get image in server side using python and store value of image in varbinary format in sql

I am trying to get value of image to server side using python and want to store it in sql db. I need to store image value as varbinary format in sql server. How do I do that? If anybody has an idea please share them with me.
So if you want to store the url you can do it with mysql shell or python code like this :
shell:
mysql> create table `index` (url varchar(50));
Query OK, 0 rows affected (0.05 sec)
mysql> insert into `index`(url) values ('http://www.google.com');
Query OK, 1 row affected (0.00 sec)
python:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb as mdb
con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS Writers")
cur.execute("CREATE TABLE Writers(Id INT PRIMARY KEY AUTO_INCREMENT, \
Name VARCHAR(25))")
cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")
for more informations see this links:
zetcode
stack question

Use of "Key" with adodbapi connection to MS Access

I have some code that links to Access and works fine with adodbapi, except for one niggling issue which I cant resolve. Basically I want to create a new table in Access with the Column Headings "Key" and "Value" but it doenst seem to work unless I include the commas which I dont want.
I get the following error:
adodbapi.adodbapi.DatabaseError: (-2147352567, 'Exception occurred.', (0, u'Microsoft JET Database Engine', u'Syntax error in field definition.', None, 5003292, -2147217900), None)
import adodbapi
# create the DSN execution string and point it to the desired Database
database = 'D:\Temp.mdb'
constr = 'Provider=Microsoft.Jet.OLEDB.4.0; Data Source=%s ' % database
conn = adodbapi.connect(constr)
# create a cursor
cur = conn.cursor()
# below doesnt work
cur.execute('CREATE TABLE OtherInfo(Key VARCHAR(100), Value VARCHAR(100))')
# but this does
cur.execute('CREATE TABLE OtherInfo(Key2 VARCHAR(100), Value2 VARCHAR(100))')
# so does this
cur.execute('CREATE TABLE OtherInfo('Key' VARCHAR(100), 'Value' VARCHAR(100))')
# this also fails unless similar to above
cur.execute("INSERT INTO OtherInfo(Key,Value) VALUES('AppName','XXX')")
# close the cursor and connection
conn.commit() # this saves all of the changes made above
cur.close()
conn.close()
How can I make it insert Column headings and Data as {Key, Value} without having to resort to 'Key' etc as the program which uses this table cannot reference other names?
Thanks for any help.
Figured it out, it needs a [wrapper] to work as below:
cur.execute('CREATE TABLE OtherInfo([Key] VARCHAR(100), [Value] VARCHAR(100))')
Thanks to anyone who took the trouble to view.

DB-API with Python

I'm trying to insert some data into a local MySQL database by using MySQL Connector/Python -- apparently the only way to integrate MySQL into Python 3 without breaking out the C Compiler.
I tried all the examples that come with the package; Those who execute can enter data just fine. Unfortunately my attempts to write anything into my tables fail.
Here is my code:
import mysql.connector
def main(config):
db = mysql.connector.Connect(**config)
cursor = db.cursor()
stmt_drop = "DROP TABLE IF EXISTS urls"
cursor.execute(stmt_drop)
stmt_create = """
CREATE TABLE urls (
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
str VARCHAR(50) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) CHARACTER SET 'utf8'"""
cursor.execute(stmt_create)
cursor.execute ("""
INSERT INTO urls (str)
VALUES
('reptile'),
('amphibian'),
('fish'),
('mammal')
""")
print("Number of rows inserted: %d" % cursor.rowcount)
db.close()
if __name__ == '__main__':
import config
config = config.Config.dbinfo().copy()
main(config)
OUTPUT:
Number of rows inserted: 4
I orientate my code strictly on what was given to me in the examples and can't, for the life of mine, figure out what the problem is. What am I doing wrong here?
Fetching table data with the script works just fine so I am not worried about the configuration files. I'm root on the database so rights shouldn't be a problem either.
You need to add a db.commit() to commit your changes before you db.close()!

Categories