Inserting data into mySQL with python - python

Im currently using python mysql and cannot find relevant information online (ive been looking for around an hour) maybe i am miss-searching correct terms to find this relivant information.
while inputting data within a table it requires % values, i am using the following to insert strings:
query = "INSERT INTO OWNERINFO(`Name`) VALUES( %s )
i assume %s identifies strings, i am wondering how you identify other data types ie. int, tinyint, smallint, date, etc.
or if there is a specific web-page which shows thse data types which i have missed?

%s is placeholder, it can be used for integer, float also..
https://pynative.com/python-mysql-insert-data-into-database-table/

The following should do the job:
values_to_enter = ("value1", "value2")
query = "insert into <table_name> values (%s, %s)"
mycursor.execute(query, values_to_enter)

Related

How to save a very long integer data in the MYSQL Data base

I used an encryption algorithm with 265(or more) bit keys and try to save the encrypted data to a database, my encrypted data is a very big integer. I have a problem when trying to save it in the MYSQL database server. the data is saved in the database fields as continuous of '9'.Note that the types of all fields in my database are VARCHAR(), this is the code of determining fields type"
DB_Columns="(ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,CredtNo VARCHAR(700),Fname VARCHAR(700), Lname VARCHAR(700), Balance VARCHAR(1000) )"
and the statement of inserting the encryptied data using python is:
insert_stmt = (f"INSERT INTO {Tname} (PhoneNo,CryptoPhon, Fname, Lname, Balance ) VALUES (%s, %s, %s, %s, %s)")
Cursor.execute(insert_stmt, Record) # Executing the SQL command
Note that, the record is my encrypted data, and one of the value to be saved in my database is :
(2175317202645953348971113133719362660225751942313095427832814482408365145539992811710213981089606200860357565008258095906567757394686551412950904123490993298692780332626039419440732654731110306170537866185857978741870335596755093012097029150 )of type integer
Now when I want to retrieve my encrypted data from the database it will be like this:
'9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.........99'
Can I know what is the problem, and how to solve it?
I am not that familiar with MySQL but maybe you could use
VARBINARY or a BLOB like data type.

Not enough arguments for format string error when inserting list into database SQL Python

I'm trying to insert a list into separate columns of a database
print inserter
params = ['%s' for item in inserter]
sql_query = 'INSERT INTO tablename (coloumn1, coloumn2, coloumn3, coloumn4, coloumn5, coloumn6, coloumn7) VALUES (%s,%s,%s,%s,%s,%s,%s);' % ','.join(params)
cursor.execute(sql_query)
db.commit
But keep getting the error
not enough arguments for format string
Anyone know what I am doing wrong?
Anyone know what I am doing wrong?
You are using string interpolation in a query.
This is bad, mainly for 2 reasons:
It is erroneous as you see. The python interpreter is confused between the %s for the interpolation and the %s for the sql parameters.
It makes your code vulnerable for sql injection.
You should use a parametrized query:
sql_query = '''INSERT INTO tablename (coloumn1, coloumn2, coloumn3,
coloumn4, coloumn5, coloumn6, coloumn7)
VALUES (%s,%s,%s,%s,%s,%s,%s);'''
cursor.execute(sql_query, inserter) # assuming inserter is a tuple/list of values

dynamic table mysqldb python string/int issue

I am receiving an error when trying to write data to a database table when using a variable for the table name that I do not get when using a static name. For some reason on the line where I insert, if I insert an integer as the column values the code runs and the table is filled, however, if I try to use a string I get a SQL syntax error
cursor = db.cursor()
cursor.execute('DROP TABLE IF EXISTS %s' %data[1])
sql ="""CREATE TABLE %s (IP TEXT, AVAILIBILITY INT)""" %data[1]
cursor.execute(sql)
for key in data[0]:
cur_ip = key.split(".")[3]
cursor.execute("""INSERT INTO %s VALUES (%s,%s)""" %(data[1],key,data[0][key]))
db.commit()
the problem is where I have %(data[1], key, data[0][key]) any ideas?
It's a little hard to analyse your problem when you don't post the actual error, and since we have to guess what your data actually is. But some general points as advise:
Using a dynamic table name is often not way DB-systems want to be used. Try thinking if the problem could be used by using a static table name and adding an additional key column to your table. Into that field you can put what you did now as a dynamic table name. This way the DB might be able to better optimize your queries, and your queries are less likely to get errors (no need to create extra tables on the fly for once, which is not a cheap thing to do. Also you would not have a need for dynamic DROP TABLE queries, which could be a security risk.
So my advice to solve your problem would be to actually work around it by trying to get rid of dynamic table names altogether.
Another problem you have is that you are using python string formatting and not parameters to the query itself. That is a security problem in itself (SQL-Injections), but also is the problem of your syntax error. When you use numbers, your expression evaluates to
INSERT INTO table_name VALUES (100, 200)
Which is valid SQL. But with strings you get
INSERT INTO table_name VALUES (Some Text, some more text)
which is not valid (since you have no quotes ' around the strings.
To get rid of your syntax problem and of the sql-injection-problem, don't add the values to the string, pass them as a list to execute():
cursor.execute("INSERT INTO table_name VALUES (%s,%s)", (key, data[0][key]))
If you must have a dynamic table name, put that in your query string first (e.g. with % formatting), and give the actual values for your query as parameters as above (since I cannot imagine that execute will accept the table name as a parameter).
To put it in some simple sample code. Right now you are trying to do it like this:
# don't do this, this won't even work!
table_name = 'some_table'
user_name = 'Peter Smith'
user_age = 47
query = "INSERT INTO %s VALUES (%s, %s)" % (table_name, user_name, user_age)
cursor.execute(query)
That creates query
INSERT INTO some_table VALUES (Peter Smith, 100)
Which cannot work, because of the unquoted string. So you needed to do:
# DON'T DO THIS, it's bad!
query = "INSERT INTO %s VALUES ('%s', %s)" % (table_name, user_name, user_age)
That's not a good idea, because you need to know where to put quotes and where not (which you will mess up at some point). Even worse, imagine a user named named Connor O'Neal. You would get a syntax error:
INSERT INTO some_table VALUES ('Connor O'Neal', 100)
(This is also the way sql-injections are used to crush your system / steal your data). So you would also need to take care of escaping the values that are strings. Getting more complicated.
Leave those problems to python and mysql, by passing the date (not the table name) as arguments to execute!
table_name = 'some_table'
user_name = 'Peter Smith'
user_age = 47
query = "INSERT INTO " + table_name + " VALUES (%s, %s)"
cursor.execute(query, (user_name, user_age))
This way you can even pass datetime objects directly. There are other ways to put the data than using %s, take a look at this examples http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html (that is python3 used there, I don't know which you use - but except of the print statements it should work with python2 as well, I think).

Inserting multiple strings into 1 table

I am trying to add 2 strings into a table.
My insert statement is:
INSERT INTO "State"
(state, relevant_id)
VALUES (%s, %s) """, state_values, relevant_id
This does not work because I am supplying too many arguments. Relevant_id is a variable that holds an integer, while state_values are values pertaining to the relevant_id.
Is there a way to insert both strings coming from 2 different variables? I am coding in python and using postgres as a db.
You should pass query parameters as a tuple in a second argument to execute:
cursor.execute("""INSERT INTO
State
(state, relevant_id)
VALUES
(%s, %s);""",
(state_values, relevant_id))
If you do it this way, you'll also get escaping to prevent sql injections for free.
Hope that helps.

What is the syntax to INSERT datetime variable INTO VALUES

What is the syntax for inserting a SQL datetime data type into a row?
The following in Python gives a NULL value for the timestamp variable only.
timestamp = datetime.datetime.today()
print timestamp
query = "INSERT INTO table1 (name, class, time_update) VALUES('ONE','TWO',#timestamp)"
cursor.execute(query)
I'm sure it depends on which database backend you're using, but in SQLite for example, you need to send your parameter as part of the query (that's what a parameterized statement is all about):
timestamp = datetime.datetime.today()
print timestamp
query = "INSERT INTO table1 (name, class, time_update) VALUES('ONE','TWO',?)"
cursor.execute(query, (timestamp,))
It really depends on the database. For MySQL, according to this, you can specify a timestamp/datetime in several formats, mostly based on ISO8601: 'YYYY-MM-DD', 'YY-MM-DD', 'YYYYMMDD' and 'YYMMDD' (without delimiters) or if you want greater precision 'YYYY-MM-DD HH:MM:SS' or 'YY-MM-DD HH:MM:SS' ('YYYYMMDDHHMMSS' or 'YYMMDDHHMMSS').
As far as querying goes you should probably parameterise (it's safer and a very good habit) by specifying a placeholder in the query string. For MySQL you could do:
query = "INSERT INTO table1 (name, class, time_update) VALUES('ONE','TWO',%s)"
cursor.execute(query, (timestamp,))
but the syntax for placeholders varies (depending on the db interface/driver) — see the documentation for your DB/Python interface.

Categories