简体   繁体   English

从 Python 重命名 SQL 中特定表中的列名

[英]Rename a Column name in a specific Table in SQL from Python

I'm trying to rename a column name in SQL-Server from Python.我正在尝试从 Python 重命名 SQL-Server 中的列名。

Code代码

def ModifeingColumnName():
    try:
        myconn = mysql.connector.connect(host ="localhost" , user = "root" , password = "", database = "test")
        mycurs = myconn.cursor()
        mycurs.execute('''EXEC SP_RENAME 'test_table.Name','First_Name','COLUMN' ''')
        myconn.commit()
        print('changed successfully!')
    except:
        print('failed!')
  • my database name is (test)我的数据库名称是(test)
  • my table is (test_table)我的表是(test_table)
  • my column name is (Name)我的专栏名称是(Name)

Issue问题

It doesn't work.它不起作用。 It always reached the except block.它总是到达 except 块。

What's the problem?有什么问题?

I'm using SQL and here is the error when i remove the try block :我正在使用 SQL,这是我删除 try 块时的错误:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; mysql.connector.errors.ProgrammingError: 1064 (42000): 你的 SQL 语法有错误; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'EXEC SP_RENAME 'test.Name','First_Name','COLUMN'' at line检查与您的 MariaDB 服务器版本相对应的手册,以获取在“EXEC SP_RENAME 'test.Name','First_Name','COLUMN'' 行附近使用的正确语法

you can use it like this:你可以像这样使用它:

# Establish connection to MySQL database
import mysql.connector
  
db = mysql.connector.connect(
  host="localhost", # your host
  user="root", # your username
  password="root123", # your password
  database = "meow" # name of the database
  )
  

mycursor = db.cursor() # cursor() method is used to create a cursor object
  
query = "ALTER TABLE persons RENAME COLUMN PersonID TO Emp_Id;" # query to rename column
mycursor.execute(query) # execute the query
  
# close the Connection
db.close() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM