python3 - psycopg2 - 执行sql文件

时间:2017-08-21 21:35:47

标签: sql postgresql python-3.x psycopg2 execute

我有这个基本的sql文件:

CREATE TABLE `app_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(200) DEFAULT NULL,
  `password` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

并希望通过python执行它:

connect_str = "dbname='dbname' user='user' host='192.168.1.101' password='password'"
conn = psycopg2.connect(connect_str)
cursor = conn.cursor()

fd = open('file.sql', 'r')
sqlFile = fd.read()
fd.close()
sqlCommands = sqlFile.split(';')
for command in sqlCommands:
    print(command)
    if command.strip() != '':
        cursor.execute(command)

当我通过" python3 app.py"执行此操作时,它会连接,但我得到:

psycopg2.ProgrammingError: syntax error at or near "`"
LINE 1: CREATE TABLE `app_users` (

但我不知道为什么......任何人都可以帮我解决这个问题?

谢谢和问候

1 个答案:

答案 0 :(得分:1)

使用正确的Postgresql语法:

CREATE TABLE app_users (
    id serial,
    email varchar(200),
    password varchar(200),
    primary key (id)
)