python使用sql批量插入数据+查看执行的语句+动态sql创建表+动态创建索引

class Test():
    cursor = connection.cursor()
    data_to_insert = []
    sql = "INSERT INTO   test_t  (id,  name ) VALUES" """ (%s, %s) """

    d = ('1', "apple")
    data_to_insert.append(d)
    d = ('2', "orange")
    data_to_insert.append(d)

    # 查看执行的sql语句
    #sql = cursor.mogrify(sql, data_to_insert)
    #print(sql)

    # 执行批量插入
    cursor.executemany(sql, data_to_insert)

    #创建表
    cursor.execute(""" CREATE TABLE  TEST_BLOCT   (
                        ID         	int   	     auto_increment		   	COMMENT 'id',
                        NAME 		VARCHAR(40)   	    NOT NULL	   	COMMENT '姓名',
                        PRIMARY KEY (ID)
                        ) ENGINE=INNODB DEFAULT CHARSET=utf8mb4 COMMENT='测试表';
                       """)

    # 创建索引
    cursor.execute(""" CREATE INDEX  TEST_BLOCT_INDEX on  TEST_BLOCT   (NAME )  ;  """)

    # 插入数据
    sql = "INSERT INTO TEST_BLOCT(ID,NAME ) VALUES (%s, %s)"
    params = [("1", "hello")]
    cursor.executemany(sql, params)

 

资源丰富的的网盘资源:网盘资源大全! 推荐一个适合零基础学习SQL的网站:不用安装数据库,在线轻松学习SQL!
posted @ 2023-09-19 18:02  万笑佛  阅读(371)  评论(0编辑  收藏  举报