【发布时间】:2013-11-23 01:31:29
【问题描述】:
我有一个包含名字、姓氏、年龄和性别的表格。我正在使用 MySQL 数据库。 在使用 MySQl db 时,我们是否需要创建表,在单个 pythonic 脚本中进行插入操作?
例如:
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost", "usename", "password", "TESTDB")
cursor = db.cursor()
cursor.execute ( """
CREATE TABLE PERSON
(
F_NAME CHAR(20) NOT NULL,
L_NAME CHAR(20),
AGE INT,
GENDER CHAR(4)
)
""")
cursor.execute( """
INSERT INTO PERSON (F_NAME, L_NAME, AGE, GENDER)
VALUES
('Neeraj','Lad','22','Male'),
('Vivek','Pal','24','Male')
""")
print cursor.rowcount
编辑代码:
#!/usr/bin/python
import MySQLdb
import cgi
print "Content-type: text/html\n"
form = cgi.FieldStorage()
f_Name = form.getvalue('firstname', '')
l_Name = form.getvalue('lastname', '')
age = form.getvalue('age', 0)
gender = form.getvalue('gender', '')
db = MySQLdb.connect(host="", user="", password="", db="")
cursor = db.cursor()
sql = "INSERT INTO PERSON (F_NAME, L_NAME, Age, Gender) VALUES (%s, %s, %s, %s)" %(f_name, l_name, age, gender)
cursor.execute(sql)
db.commit()
db.close()
【问题讨论】:
-
请不要尝试将您的问题编辑成您认为正确的答案。这个问题应该是一个有用的问题,可以通过一个有用的答案来回答。这样,如果有人和你有同样的问题,他们可以在搜索中找到你的问题,答案也会对他们有所帮助,为大家节省大量时间。
标签: python database cgi mysql-python