如何将数据插入MySQL数据库?

我想在我的MySQL数据库中插入整数188和90,但以下代码不起作用:

import MySQLdb

conn = MySQLdb.connect(host= "localhost",

user="root",

passwd="newpassword",

db="engy1")

x = conn.cursor()

x.execute("SELECT * FROM anooog1")

x.execute (" INSERT INTO anooog1 VALUES ('%s','%s') ", (188,90))

row = x.fetchall()

为什么不起作用?

回答:

#Server Connection to MySQL:

import MySQLdb

conn = MySQLdb.connect(host= "localhost",

user="root",

passwd="newpassword",

db="engy1")

x = conn.cursor()

try:

x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))

conn.commit()

except:

conn.rollback()

conn.close()

为我工作:

>>> import MySQLdb

>>> #connect to db

... db = MySQLdb.connect("localhost","root","password","testdb" )

>>>

>>> #setup cursor

... cursor = db.cursor()

>>>

>>> #create anooog1 table

... cursor.execute("DROP TABLE IF EXISTS anooog1")

__main__:2: Warning: Unknown table 'anooog1'

0L

>>>

>>> sql = """CREATE TABLE anooog1 (

... COL1 INT,

... COL2 INT )"""

>>> cursor.execute(sql)

0L

>>>

>>> #insert to table

... try:

... cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))

... db.commit()

... except:

... db.rollback()

...

1L

>>> #show table

... cursor.execute("""SELECT * FROM anooog1;""")

1L

>>> print cursor.fetchall()

((188L, 90L),)

>>>

>>> db.close()

在MySQL表;

mysql> use testdb;

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

Database changed

mysql> SELECT * FROM anooog1;

+------+------+

| COL1 | COL2 |

+------+------+

| 188 | 90 |

+------+------+

1 row in set (0.00 sec)

mysql>

以上是 如何将数据插入MySQL数据库? 的全部内容, 来源链接: utcz.com/qa/409542.html

回到顶部