使用 python 将单个变量插入 PostgreSQL 中的 table
Insert a single variable into a table in PostgreSQL using python
我正在尝试将单个值插入到具有两列的 Postgres table 中。第一列是一个自动增加的主键,而第二列应该是一个变量。我做了一些研究并找到了以下资源 TypeError: not all arguments converted during string formatting python, How to set auto increment primary key in PostgreSQL? this Psycopg2 string formatting with variable names for type creation。
import psycopg2
try:
conn = psycopg2.connect("dbname=postgres user=postgres password=actuarial")
print("database created successfully.")
except psycopg2.OperationalError as ex:
print("Connection failed: {0}".format(ex))
cur = conn.cursor()
def create_client_table():
cur.execute("CREATE TABLE ClientTable (ClientID SERIAL PRIMARY KEY, Name varchar);")
print('student table created successfully')
create_client_table()
def client_add():
name = input("Enter the names of the student:")
cur.execute("INSERT INTO CleintTable VALUES (%s)", (name));
cur.execute("SELECT * FROM StudentTable")
rows = cur.fetchall()
print(rows)
client_add()
conn.close()
根据 运行 上面的代码,我得到以下错误。请帮我找出我哪里出错了。
cur.execute("INSERT INTO CleintTable VALUES (%s)", (name));
TypeError: not all arguments converted during string formatting
在 name
之后需要一个逗号才能将带括号的表达式转换为元组:
cur.execute("INSERT INTO CleintTable VALUES (%s)", (name,));
否则它是一个字符串序列,execute
方法将对其进行迭代。
“CleintTable”可能需要更改为 ClientTable,除非您有意以这种方式命名 table。除了您正在寻找的内容之外,我在阅读您的代码时注意到了一些事情。
我正在尝试将单个值插入到具有两列的 Postgres table 中。第一列是一个自动增加的主键,而第二列应该是一个变量。我做了一些研究并找到了以下资源 TypeError: not all arguments converted during string formatting python, How to set auto increment primary key in PostgreSQL? this Psycopg2 string formatting with variable names for type creation。
import psycopg2
try:
conn = psycopg2.connect("dbname=postgres user=postgres password=actuarial")
print("database created successfully.")
except psycopg2.OperationalError as ex:
print("Connection failed: {0}".format(ex))
cur = conn.cursor()
def create_client_table():
cur.execute("CREATE TABLE ClientTable (ClientID SERIAL PRIMARY KEY, Name varchar);")
print('student table created successfully')
create_client_table()
def client_add():
name = input("Enter the names of the student:")
cur.execute("INSERT INTO CleintTable VALUES (%s)", (name));
cur.execute("SELECT * FROM StudentTable")
rows = cur.fetchall()
print(rows)
client_add()
conn.close()
根据 运行 上面的代码,我得到以下错误。请帮我找出我哪里出错了。
cur.execute("INSERT INTO CleintTable VALUES (%s)", (name));
TypeError: not all arguments converted during string formatting
在 name
之后需要一个逗号才能将带括号的表达式转换为元组:
cur.execute("INSERT INTO CleintTable VALUES (%s)", (name,));
否则它是一个字符串序列,execute
方法将对其进行迭代。
“CleintTable”可能需要更改为 ClientTable,除非您有意以这种方式命名 table。除了您正在寻找的内容之外,我在阅读您的代码时注意到了一些事情。