创建连接:connect
创建游标:cursor
执行sql:excute,excutemany
关闭连接:close
参数化sql:%s
例子:
#encoding=utf-8 from mysql import connector #创建连接params = dict(host = ‘localhost‘, port = 3306, user = ‘root‘, password = ‘123456‘, database = ‘test‘)conn = connector.connect(**params) #创建游标cursor = conn.cursor() #执行sql语句# ddl = """# create table users(id INTEGER , name VARCHAR(40), address VARCHAR(100))# """ #cursor.execute(ddl)#先到数据库中将id改为自增长,主键. sqltext = """ insert into users(name,address) VALUES (‘tina‘,‘beijing‘)"""cursor.execute(sqltext) #如果不加下面这句代码,表中则无法添加内容,会显示空.conn.commit() sqltext = """ select * from users""" cursor.execute(sqltext) for row in cursor: print row #%s代表参数sqltemplate = """ insert into users(name,address) values (%s, %s)"""ul = (‘demo‘, ‘shanghai‘) cursor.execute(sqltemplate, ul)conn.commit() us = [ (‘tina1‘, ‘abc‘), (‘tina2‘, ‘abc‘), (‘tina3‘, ‘abc‘), (‘tina4‘, ‘abc‘), (‘tina5‘, ‘abc‘), (‘tina6‘, ‘abc‘)] #executemany可以批量执行语句cursor.executemany(sqltemplate, us)conn.commit() #关闭连接conn.close()
时间: 2024-10-10 02:10:05