Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python MySql Insert not working

Tags:

python

mysql

I am using python MySQL API to connect to Mysql database from python program. I am facing a problem from few days. I am unable to insert records into the database and dont know whats the reason. Here is the way i connect and insert records into the database.

db = MySQLdb.connect("localhost","root","padmaramulu","pdfsearch" ) cursor = db.cursor() #cursor.execute("""CREATE TABLE IF NOT EXISTS documents (docid INT NOT NULL ,PRIMARY KEY(docid),docname CHAR(30)) engine=innodb""") temp = "hello";number = 2; cursor.execute( 'insert into documents(docid,docname) values("%d","%s")' % (number,temp) ) db.close() 

Why is it so?

like image 275
nikhil Avatar asked May 17 '11 06:05

nikhil


People also ask

What does the Executemany () method do?

executemany() Method. This method prepares a database operation (query or command) and executes it against all parameter sequences or mappings found in the sequence seq_of_params . In Python, a tuple containing a single value must include a comma.

How do you add user input to a database in python?

connect ( 'mydatabase. db' ) cursor = conn. cursor () #create the salesman table cursor. execute("CREATE TABLE salesman(salesman_id n(5), name char(30), city char(35), commission decimal(7,2));") s_id = input('Salesman ID:') s_name = input('Name:') s_city = input('City:') s_commision = input('Commission:') cursor.


2 Answers

Before closing the connection, you should add db.commit().

like image 51
miette Avatar answered Sep 17 '22 13:09

miette


if you are using InnoDB engine in MySQL you should add

db.commit()  

else change your MySQL engine into MyISAM no need to change anything in code.

like image 38
Muthamizhchelvan. V Avatar answered Sep 19 '22 13:09

Muthamizhchelvan. V