I am trying to insert values to mysql using python but the code is not working, its returning a blank page & no values written in database table, Please help me
import MySQLdb as mdb
con = mdb.connect('localhost', 'python', '123456', 'python');
cur = con.cursor()
cur.execute("INSERT INTO test VALUES('234','566789','rohan','rajesh','78979','Maths','25','50','75','P')")
cur.commit()
cur.close()
con.close()
Try this instead:
import MySQLdb as mdb
con = mdb.connect(host='localhost', user='python', passwd='123456', db='python');
cur = con.cursor()
cur.execute("INSERT INTO test(ecode) VALUES('Manoj')")
cur.execute("INSERT INTO test(htno) VALUES('Manoj')")
cur.execute("INSERT INTO test(name) VALUES('Manoj')")
cur.execute("INSERT INTO test(fathername) VALUES('Manoj')")
cur.execute("INSERT INTO test(subcode) VALUES('Manoj')")
cur.execute("INSERT INTO test(subject) VALUES('Manoj')")
cur.execute("INSERT INTO test(internals) VALUES('Manoj')")
cur.execute("INSERT INTO test(externals) VALUES('Manoj')")
cur.execute("INSERT INTO test(total) VALUES('Manoj')")
cur.execute("INSERT INTO test(result) VALUES('Manoj')")
cur.commit()
cursor.close()
con.close()
There were several problems:
python
variable success
variable MySQLdb
Though, I don't understand why do you need to insert rows with Manoj
value in different fields.
UPD, you have an error in your sql syntax (missing quote char before 566789
):
cur.execute("INSERT INTO test VALUES('234','566789','rohan','rajesh','78979','Maths','25','50','75','P')")
Hope that helps.
Your Python string must be exactly as in a normal MySQL statement, so a good idea is to try executing it at the MySQL prompt to see what it returns. Without specifying the fields eg
INSERT INTO FOO VALUES (4, 5, 6)
instead of
INSERT INTO FOO (X, Y, Z) VALUES (4, 5, 6)
will insert values in the order they are defined in the table (as shown using the DESCRIBE
command) but is generally not a good idea in case for example the layout of the table changes.
You need to ensure that all your strings have opening and closing quotes - your 566789
string doesn't in the example you have given. Also you are passing what appear to be integers as strings. If they are defined as integers in the table you will need to remove the quotes.
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.