我有一个包含名字、姓氏、年龄和性别的表格。我正在使用 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()