0

我正在尝试使用 python 向 mysql 插入值,但代码不起作用,它返回一个空白页并且没有写入数据库表中的值,请帮助我

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()
4

2 回答 2

0

试试这个:

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()

有几个问题:

  • 未定义的python变量
  • 未定义的success变量
  • 上下文管理器不支持MySQLdb

不过,我不明白为什么需要Manoj在不同的字段中插入具有值的行。

UPD,您的 sql 语法有错误(在 之前缺少引号字符566789):

cur.execute("INSERT INTO test VALUES('234','566789','rohan','rajesh','78979','Maths','25','50','75','P')")

希望有帮助。

于 2013-07-16T11:51:54.073 回答
0

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 e.g.

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.

于 2013-07-16T13:19:10.193 回答