Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert list into my database using Python [duplicate]

Tags:

python

sql

mysql

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

like image 406
mauguerra Avatar asked Nov 29 '11 18:11

mauguerra


People also ask

How do you insert multiple rows in SQL using Python?

Method 1: Inserting Values through Naive method In this method, we import the psycopg2 package and form a connection using the psycopg2. connect() method, we connect to the 'Classroom' database. after forming a connection we create a cursor using the connect(). cursor() method, it'll help us fetch rows.

How do I insert a list of values in SQL?

To insert a row into a table, you need to specify three things: First, the table, which you want to insert a new row, in the INSERT INTO clause. Second, a comma-separated list of columns in the table surrounded by parentheses. Third, a comma-separated list of values surrounded by parentheses in the VALUES clause.


1 Answers

Your question is not clear.

Do you want to insert the list as a comma-delimited text string into a single column in the database? Or do you want to insert each element into a separate column? Either is possible, but the technique is different.

Insert comma-delimited list into one column:

 conn.execute('INSERT INTO table (ColName) VALUES (?);', [','.join(list)])

Insert into separate columns:

  params = ['?' for item in list]
  sql    = 'INSERT INTO table (Col1, Col2. . .) VALUES (%s);' % ','.join(params)
  conn.execute(sql, list)

both assuming you have established a connection name conn.

A few other suggestions:

  • Try to avoid INSERT statements that do not list the names and order of the columns you're inserting into. That kind of statement leads to very fragile code; it breaks if you add, delete, or move columns around in your table.

  • If you're inserting a comma-separted list into a single-field, that generally violates principals of database design and you should use a separate table with one value per record.

  • If you're inserting into separate fields and they have names like Word1 and Word2, that is likewise an indication that you should be using a separate table instead.

  • Never use direct string substitution to create SQL statements. It will break if one of the values is, for example o'clock. It also opens you to attacks by people using SQL injection techniques.

like image 65
Larry Lustig Avatar answered Sep 27 '22 19:09

Larry Lustig