使用cursor.mogrify从元组列表中将行插入db会产生错误

时间:2017-02-02 10:11:03

标签: python postgresql psycopg2

我正在尝试使用cursor.mogrify使用此psycopg2: insert multiple rows with one query

将大量行插入postgres

data是一个元组列表,其中每个元组都是需要插入的行。

TypeError: sequence item 0: expected str instance, bytes found

但收到错误:

  args_str = ','.join(cursor.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in data)

在线:

//buttons.js

import React from 'react';
import ReactDOM from 'react-dom';

class Button extends React.Component {

  render() {
    const {children, className, href, icon} = this.props;
    const props = {href, className, ref: 'button', disabled: this.props.disabled };
    const element = href ? 'a' : 'button';

    return React.createElement(
      element, props, icon ? <i className={this.props.icon} /> : null, children
    );
  }
}

//index.js

import React from 'react';
import ReactDOM from 'react-dom';

import Button from './components/buttons';

ReactDOM.render(
  <div>
    <Button className="btn-primary">click me</Button>
    <Button className="btn-success" icon="fa fa-phone">success </Button>
    <Button className="btn-success" disabled={true}>disabled </Button>
  </div>, 
  document.getElementById('root')
);

//index.html 

<!doctype html>
<html>
  <head>

    <title></title>

  </head>
  <body>

        <div id='root'></div>

    <script src="/bundle.js"></script>
  </body>
</html>

如果我尝试更改为 b&#39; .join(cursor.mogrify(&#34;(%s,%s,%s,%s,%s,%s, %s,%s)&#34;,x)数据中的x), 然后执行查询给出插入字节的错误....

我做错了吗?

2 个答案:

答案 0 :(得分:3)

data = [(1,2),(3,4)]
args_str = ','.join(['%s'] * len(data))
sql = "insert into t (a, b) values {}".format(args_str)
print (cursor.mogrify(sql, data).decode('utf8'))
#cursor.execute(sql, data)

输出:

insert into t (a, b) values (1, 2),(3, 4)

答案 1 :(得分:2)

您可以执行类似的操作,但验证dict值以防止sql注入。

>>> from psycopg2.extensions import AsIs
>>> _insert_sql = 'INSERT INTO myTable (%s) VALUES %s RETURNING id'    
>>> data = {"col_1": "val1", "col_2": "val2"}
>>> values = (AsIs(','.join(data.keys())), tuple(data.values()))
>>> print(cur.mogrify(_insert_sql, values))
b"INSERT INTO myTable (col_1,col_2) VALUES ('val1', 'val2') RETURNING id"