Insert list into my database using Python

I want to insert a list in my database but I can't.

Here is an example of what I need:

variable_1 = "HELLO"
variable_2 = "ADIOS"
list = [variable_1,variable_2]

INSERT INTO table VALUES ('%s') % list

Can something like this be done? Can I insert a list as a value? When I try it, an error says that is because of an error in MySQL syntax

Answers


The answer to your original question is: No, you can't insert a list like that.

However, with some tweaking, you could make that code work by using %r and passing in a tuple:

variable_1 = "HELLO"
variable_2 = "ADIOS"
varlist = [variable_1, variable_2]
print "INSERT INTO table VALUES %r;" % (tuple(varlist),)

Unfortunately, that style of variable insertion leaves your code vulnerable to SQL injection attacks.

Instead, we recommend using Python's DB API and building a customized query string with multiple question marks for the data to be inserted:

variable_1 = "HELLO"
variable_2 = "ADIOS"
varlist = [variable_1,variable_2]
var_string = ', '.join('?' * len(varlist))
query_string = 'INSERT INTO table VALUES (%s);' % var_string
cursor.execute(query_string, varlist)

The example at the beginning of the SQLite3 docs shows how to pass arguments using the question marks and it explains why they are necessary (essentially, it assures correct quoting of your variables).


Need Your Help

LINQ to SQL Join and If Condition

c# linq join if-statement condition

I have the query below where I want to set the price if bstock is not null and bstock.Price (bstock.Price is a null-able doubel? ) is not null. The join is a left outer join. Can someone help me?

Pass list of links to Django Template

python django templates django-templates django-views

I have a list of urls that I have imported in my settings.py file via:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.