desc table tableName 与 show create table tableName 的区别

本文介绍了如何使用showcreatetable命令查看创建表的具体语句,并通过desctable命令获取已创建表的详细描述,包括字段名称、类型及主键设置等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

show create tableg表示的是创建表的具体语句,如下图

效果

2.desc table 表示的创建好的表的描述,字段名称,类型,是否为主键等,以表格的形式存在

效果

 

 

""" title: SQL Server Access author: MENG author_urls: - https://github.com/mengvision description: A tool for reading database information and executing SQL queries, supporting multiple databases such as MySQL, PostgreSQL, SQLite, and Oracle. It provides functionalities for listing all tables, describing table schemas, and returning query results in CSV format. A versatile DB Agent for seamless database interactions. required_open_webui_version: 0.5.4 requirements: pymysql, sqlalchemy, cx_Oracle version: 0.1.6 licence: MIT # Changelog ## [0.1.6] - 2025-03-11 ### Added - Added `get_table_indexes` method to retrieve index information for a specific table, supporting MySQL, PostgreSQL, SQLite, and Oracle. - Enhanced metadata capabilities by providing detailed index descriptions (e.g., index name, columns, and type). - Improved documentation to include the new `get_table_indexes` method and its usage examples. - Updated error handling in `get_table_indexes` to provide more detailed feedback for unsupported database types. ## [0.1.5] - 2025-01-20 ### Changed - Updated `list_all_tables` and `table_data_schema` methods to accept `db_name` as a function parameter instead of using `self.valves.db_name`. - Improved flexibility by decoupling database name from class variables, allowing dynamic database selection at runtime. ## [0.1.4] - 2025-01-17 ### Added - Added support for Oracle database using `cx_Oracle` driver. - Added dynamic engine creation in each method to ensure fresh database connections for every operation. - Added support for Oracle-specific queries in `list_all_tables` and `table_data_schema` methods. ### Changed - Moved `self._get_engine()` from `__init__` to individual methods for better flexibility and tool compatibility. - Updated `_get_engine` method to support Oracle database connection URL. - Improved `table_data_schema` method to handle Oracle-specific column metadata. ### Fixed - Fixed potential connection issues by ensuring each method creates its own database engine. - Improved error handling for Oracle-specific queries and edge cases. ## [0.1.3] - 2025-01-17 ### Added - Added support for multiple database types (e.g., MySQL, PostgreSQL, SQLite) using SQLAlchemy. - Added configuration flexibility through environment variables or external configuration files. - Enhanced query security with stricter validation and SQL injection prevention. - Improved error handling with detailed exception messages for better debugging. ### Changed - Replaced `pymysql` with SQLAlchemy for broader database compatibility. - Abstracted database connection logic into a reusable `_get_engine` method. - Updated `table_data_schema` method to support multiple database types. ### Fixed - Fixed potential SQL injection vulnerabilities in query execution. - Improved handling of edge cases in query validation and execution. ## [0.1.2] - 2025-01-16 ### Added - Added support for specifying the database port with a default value of `3306`. - Abstracted database connection logic into a reusable `_get_connection` method. ## [0.1.1] - 2025-01-16 ### Added - Support for additional read-only query types: `SHOW`, `DESCRIBE`, `EXPLAIN`, and `USE`. - Enhanced query validation to block sensitive keywords (e.g., `INSERT`, `UPDATE`, `DELETE`, `CREATE`, `DROP`, `ALTER`). ### Fixed - Improved handling of queries starting with `WITH` (CTE queries). - Fixed case sensitivity issues in query validation. ## [0.1.0] - 2025-01-09 ### Initial Release - Basic functionality for listing tables, describing table schemas, and executing `SELECT` queries. - Query results returned in CSV format. """ import os from typing import List, Dict, Any from pydantic import BaseModel, Field import re from sqlalchemy import create_engine, text from sqlalchemy.engine.base import Engine from sqlalchemy.exc import SQLAlchemyError class Tools: class Valves(BaseModel): db_host: str = Field( default="localhost", description="The host of the database. Replace with your own host.", ) db_user: str = Field( default="admin", description="The username for the database. Replace with your own username.", ) db_password: str = Field( default="admin", description="The password for the database. Replace with your own password.", ) db_name: str = Field( default="db", description="The name of the database. Replace with your own database name.", ) db_port: int = Field( default=3306, # Oracle 默认端口 description="The port of the database. Replace with your own port.", ) db_type: str = Field( default="mysql", description="The type of the database (e.g., mysql, postgresql, sqlite, oracle).", ) def __init__(self): """ Initialize the Tools class with the credentials for the database. """ print("Initializing database tool class") self.citation = True self.valves = Tools.Valves() def _get_engine(self) -> Engine: """ Create and return a database engine using the current configuration. """ if self.valves.db_type == "mysql": db_url = f"mysql+pymysql://{self.valves.db_user}:{self.valves.db_password}@{self.valves.db_host}:{self.valves.db_port}/{self.valves.db_name}" elif self.valves.db_type == "postgresql": db_url = f"postgresql://{self.valves.db_user}:{self.valves.db_password}@{self.valves.db_host}:{self.valves.db_port}/{self.valves.db_name}" elif self.valves.db_type == "sqlite": db_url = f"sqlite:///{self.valves.db_name}" elif self.valves.db_type == "oracle": db_url = f"oracle+cx_oracle://{self.valves.db_user}:{self.valves.db_password}@{self.valves.db_host}:{self.valves.db_port}/?service_name={self.valves.db_name}" else: raise ValueError(f"Unsupported database type: {self.valves.db_type}") return create_engine(db_url) def list_all_tables(self, db_name: str) -> str: """ List all tables in the database. :param db_name: The name of the database. :return: A string containing the names of all tables. """ print("Listing all tables in the database") engine = self._get_engine() # 动态创建引擎 try: with engine.connect() as conn: if self.valves.db_type == "mysql": result = conn.execute(text("SHOW TABLES;")) elif self.valves.db_type == "postgresql": result = conn.execute( text( "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';" ) ) elif self.valves.db_type == "sqlite": result = conn.execute( text("SELECT name FROM sqlite_master WHERE type='table';") ) elif self.valves.db_type == "oracle": result = conn.execute(text("SELECT table_name FROM user_tables;")) else: return "Unsupported database type." tables = [row[0] for row in result.fetchall()] if tables: return ( "Here is a list of all the tables in the database:\n\n" + "\n".join(tables) ) else: return "No tables found." except SQLAlchemyError as e: return f"Error listing tables: {str(e)}" def get_table_indexes(self, db_name: str, table_name: str) -> str: """ Get the indexes of a specific table in the database. :param db_name: The name of the database. :param table_name: The name of the table. :return: A string describing the indexes of the table. """ print(f"Getting indexes for table: {table_name}") engine = self._get_engine() try: key, cloumn = 0, 1 with engine.connect() as conn: if self.valves.db_type == "mysql": query = text(f"SHOW INDEX FROM {table_name}") key, cloumn = 2, 4 elif self.valves.db_type == "postgresql": query = text( """ SELECT indexname, indexdef FROM pg_indexes WHERE tablename = :table_name; """ ) elif self.valves.db_type == "sqlite": query = text( """ PRAGMA index_list(:table_name); """ ) elif self.valves.db_type == "oracle": query = text( """ SELECT index_name, column_name FROM user_ind_columns WHERE table_name = :table_name; """ ) else: return "Unsupported database type." result = conn.execute(query) indexes = result.fetchall() if not indexes: return f"No indexes found for table: {table_name}" description = f"Indexes for table '{table_name}':\n" for index in indexes: description += f"- {index[key]}: {index[cloumn]}\n" return description # result = conn.execute(query) # description = result.fetchall() # if not description: # return f"No indexes found for table: {table_name}" # column_names = result.keys() # description = f"Query executed successfully. Below is the actual result of the query {query} running against the database in CSV format:\n\n" # description += ",".join(column_names) + "\n" # for row in description: # description += ",".join(map(str, row)) + "\n" # return description except SQLAlchemyError as e: return f"Error getting indexes: {str(e)}" def table_data_schema(self, db_name: str, table_name: str) -> str: """ Describe the schema of a specific table in the database, including column comments. :param db_name: The name of the database. :param table_name: The name of the table to describe. :return: A string describing the data schema of the table. """ print(f"Database: {self.valves.db_name}") print(f"Describing table: {table_name}") engine = self._get_engine() # 动态创建引擎 try: with engine.connect() as conn: if self.valves.db_type == "mysql": query = text( " SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, COLUMN_COMMENT " " FROM INFORMATION_SCHEMA.COLUMNS " f" WHERE TABLE_SCHEMA = '{self.valves.db_name}' AND TABLE_NAME = '{table_name}';" ) elif self.valves.db_type == "postgresql": query = text( """ SELECT column_name, data_type, is_nullable, column_default, '' FROM information_schema.columns WHERE table_name = :table_name; """ ) elif self.valves.db_type == "sqlite": query = text("PRAGMA table_info(:table_name);") elif self.valves.db_type == "oracle": query = text( """ SELECT column_name, data_type, nullable, data_default, comments FROM user_tab_columns LEFT JOIN user_col_comments ON user_tab_columns.table_name = user_col_comments.table_name AND user_tab_columns.column_name = user_col_comments.column_name WHERE user_tab_columns.table_name = :table_name; """ ) else: return "Unsupported database type." # result = conn.execute( # query, {"db_name": db_name, "table_name": table_name} # ) result = conn.execute(query) columns = result.fetchall() if not columns: return f"No such table: {table_name}" description = ( f"Table '{table_name}' in the database has the following columns:\n" ) for column in columns: if self.valves.db_type == "sqlite": column_name, data_type, is_nullable, _, _, _ = column column_comment = "" elif self.valves.db_type == "oracle": ( column_name, data_type, is_nullable, data_default, column_comment, ) = column else: ( column_name, data_type, is_nullable, column_key, column_comment, ) = column description += f"- {column_name} ({data_type})" if is_nullable == "YES" or is_nullable == "Y": description += " [Nullable]" if column_key == "PRI": description += " [Primary Key]" if column_comment: description += f" [Comment: {column_comment}]" description += "\n" return description except SQLAlchemyError as e: return f"Error describing table: {str(e)}" def execute_read_query(self, query: str) -> str: """ Execute a read query and return the result in CSV format. :param query: The SQL query to execute. :return: A string containing the result of the query in CSV format. """ print(f"Executing query: {query}") normalized_query = query.strip().lower() if not re.match( r"^\s*(select|with|show|describe|desc|explain|use)\s", normalized_query ): return "Error: Only read-only queries (SELECT, WITH, SHOW, DESCRIBE, EXPLAIN, USE) are allowed. CREATE, DELETE, INSERT, UPDATE, DROP, and ALTER operations are not permitted." sensitive_keywords = [ "insert", "update", "delete", "create", "drop", "alter", "truncate", "grant", "revoke", "replace", ] for keyword in sensitive_keywords: if re.search(rf"\b{keyword}\b", normalized_query): return f"Error: Query contains a sensitive keyword '{keyword}'. Only read operations are allowed." engine = self._get_engine() # 动态创建引擎 try: with engine.connect() as conn: result = conn.execute(text(query)) rows = result.fetchall() if not rows: return "No data returned from query." column_names = result.keys() csv_data = f"Query executed successfully. Below is the actual result of the query {query} running against the database in CSV format:\n\n" csv_data += ",".join(column_names) + "\n" for row in rows: csv_data += ",".join(map(str, row)) + "\n" return csv_data except SQLAlchemyError as e: return f"Error executing query: {str(e)}" 将上面的工具连接到Microsoft sql server
07-23
<think>我们被要求将上述工具连接到Microsoft SQL Server。从代码中我们可以看到,目前支持MySQL、PostgreSQL、SQLite和Oracle。我们需要添加对SQL Server的支持。 主要修改点: 1. 在`_get_engine`方法中,添加SQL Server(mssql)的支持。SQL Server可以使用pyodbc或pymssql作为驱动。这里我们选择使用pymssql(因为requirements中没有pyodbc,但注意:原requirements中也没有pymssql,所以需要添加依赖。但根据题目要求,我们只修改代码,依赖需要用户自行安装或后续添加)。 不过,在SQLAlchemy中,SQL Server的连接字符串格式为: mssql+pymssql://<username>:<password>@<host>:<port>/<database> 或者使用pyodbc(但这里我们使用pymssql,因为原工具中已有pymysql,而pymssql类似)。 2. 在`list_all_tables`方法中,添加SQL Server的查询语句。SQL Server中,可以通过以下查询获取当前数据库的所有表: SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' 3. 在`get_table_indexes`方法中,添加SQL Server的索引查询。SQL Server中,可以通过以下查询获取表的索引信息: EXEC sp_helpindex @objname = N'table_name' 但是,sp_helpindex返回的结果集包含index_name, index_description, index_keys。我们可以这样处理: key = 0 (index_name), column = 2 (index_keys) ?但是注意返回的列顺序。 另一种方式是查询系统视图,例如: SELECT i.name AS index_name, c.name AS column_name FROM sys.indexes i JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id WHERE i.object_id = OBJECT_ID('table_name') AND i.is_primary_key = 0 AND i.is_unique_constraint = 0 AND i.is_unique = 0 -- 或者根据需要调整 ORDER BY i.name, ic.key_ordinal; 但是考虑到复杂度,我们可以使用sp_helpindex,因为它简单。但是注意,sp_helpindex返回的结果是一个表,包含三列:index_name, index_description, index_keys。 其中index_keys是以逗号分隔的列名。我们可以这样展示: index_name: index_keys 所以,我们可以这样: query = text(f"EXEC sp_helpindex @objname = N'{table_name}'") key, column = 0, 2 # 因为返回的列是:index_name, index_description, index_keys 4. 在`table_data_schema`方法中,添加SQL Server的表结构查询。SQL Server中,可以通过以下查询获取表结构: SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, '' AS COLUMN_COMMENT -- SQL Server没有直接的列注释,需要从其他表获取,这里先忽略 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = :table_name 但是,注释信息需要从sys.extended_properties获取,比较复杂。为了简单,我们可以先不返回注释。 5. 注意:在SQL Server中,数据库名称(db_name)在连接字符串中已经指定,所以我们在查询时不需要指定数据库(因为连接已经指定了数据库)。但是,在查询INFORMATION_SCHEMA.COLUMNS时,我们需要指定TABLE_CATALOG(即数据库名)?实际上,INFORMATION_SCHEMA.COLUMNS会默认当前数据库。 6. 另外,在连接字符串中,SQL Server的端口默认是1433。 7. 由于SQL Server的注释信息存储在不同的系统视图中,我们暂时不获取注释。如果后续需要,可以添加。 8. 在`execute_read_query`方法中,我们不需要修改,因为已经通过正则表达式限制了只读操作,并且SQL Server的SELECT等查询语法是兼容的。 9. 在`Valves`类中,db_type的默认值还是mysql,我们可以不用改,但是用户需要指定db_type为'mssql'。 10. 注意:由于我们使用了pymssql,需要在requirements中添加pymssql。但原requirements中只有pymysql, sqlalchemy, cx_Oracle。所以,我们需要在requirements中增加pymssql。但是,题目要求我们只修改代码,所以我们在代码中不修改requirements,但需要在文档中说明。 由于题目要求修改代码,我们只修改代码部分。在代码中,我们添加对mssql的支持。 修改步骤: 1. 在_get_engine方法中,添加mssql分支: elif self.valves.db_type == "mssql": db_url = f"mssql+pymssql://{self.valves.db_user}:{self.valves.db_password}@{self.valves.db_host}:{self.valves.db_port}/{self.valves.db_name}" 2. 在list_all_tables方法中,添加mssql分支: elif self.valves.db_type == "mssql": result = conn.execute(text("SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE';")) 3. 在get_table_indexes方法中,添加mssql分支: elif self.valves.db_type == "mssql": query = text(f"EXEC sp_helpindex @objname = N'{table_name}'") key, column = 0, 2 # 返回的列:index_name, index_description, index_keys 4. 在table_data_schema方法中,添加mssql分支: elif self.valves.db_type == "mssql": query = text( "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, '', '' " # 这里我们暂时不获取主键和注释 "FROM INFORMATION_SCHEMA.COLUMNS " "WHERE TABLE_NAME = :table_name;" ) # 注意:这里我们没有处理主键和注释。主键可以通过其他方式获取,但为了简化,先不处理。 但是,为了保持一致性,我们可以尝试获取主键?原代码中对于MySQL有主键标记。在SQL Server中,我们可以通过以下方式获取主键: 我们可以修改查询,使用LEFT JOIN到主键信息,但这样会复杂。为了简化,我们先不显示主键。 因此,在描述表结构时,对于SQL Server,我们只显示列名、类型、是否可为空,不显示主键和注释。 5. 由于SQL Server的INFORMATION_SCHEMA.COLUMNS中没有列注释,我们可以通过以下方式获取注释(可选,但题目没有要求,我们可以先不做): 但是,为了功能完整性,我们可以尝试获取注释。不过,这需要额外的查询。考虑到时间,我们暂时不实现。 6. 另外,注意在SQL Server中,表名和列名可能是大小写敏感的?这取决于数据库的设置。我们这里使用大写,因为INFORMATION_SCHEMA中的列名是大写的。 但是,我们注意到在代码中,其他数据库的列名我们也是按照大写来取的(比如MySQL的INFORMATION_SCHEMA.COLUMNS中的列名是大写)。所以,在mssql分支中,我们使用大写的列名。 修改代码: 由于原代码中,table_data_schema方法在展示时,对于非SQLite和非Oracle的数据库,使用了以下字段: column_name, data_type, is_nullable, column_key, column_comment 在mssql分支中,我们返回的查询结果有5列:COLUMN_NAME, DATA_TYPE, IS_NULLABLE, 以及两个空字符串(分别代表column_key和column_comment)。 因此,在展示时,我们会使用: column_name, data_type, is_nullable, column_key(为空), column_comment(为空) 这样,就不会显示主键和注释。 如果需要显示主键,我们可以通过以下查询判断列是否为主键: SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = :table_name AND CONSTRAINT_NAME LIKE 'PK%' 但是,这需要额外的处理,我们可以在同一个查询中合并,或者单独查询。为了不使代码过于复杂,我们暂时不处理。 所以,我们按照上述计划修改。 注意:在get_table_indexes方法中,我们使用了f-string直接拼接表名,这可能有SQL注入风险,但这里表名是工具内部传递的(非用户直接输入),且工具是内部使用,可以接受。但为了安全,我们可以使用参数化查询。但是,sp_helpindex不接受参数化查询(它是存储过程,且参数是表名,不能使用变量绑定?)。所以,我们只能拼接。 另外,在table_data_schema方法中,我们使用了参数化查询(:table_name),但是在mssql分支中,我们使用的是:table_name,所以没有问题。 修改后的代码: 由于代码较长,我们只修改相关部分。下面是在原有代码基础上添加mssql支持的部分。 注意:在_get_engine方法中,我们添加mssql分支;在其他方法中也添加相应的mssql分支。 另外,在get_table_indexes方法中,对于mssql,我们使用存储过程sp_helpindex,然后解析结果。但是,注意存储过程返回的结果集可能包含多行,我们按行处理。 但是,存储过程返回的结果集列名是:index_name, index_description, index_keys。我们取第一列(index_name)和第三列(index_keys)来展示。 修改后的代码片段: 由于整个代码较长,我们只展示修改的部分。在代码中,我们会添加以下内容: 1. 在_get_engine方法中: elif self.valves.db_type == "mssql": db_url = f"mssql+pymssql://{self.valves.db_user}:{self.valves.db_password}@{self.valves.db_host}:{self.valves.db_port}/{self.valves.db_name}" 2. 在list_all_tables方法中: elif self.valves.db_type == "mssql": result = conn.execute(text("SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE';")) 3. 在get_table_indexes方法中: elif self.valves.db_type == "mssql": query = text(f"EXEC sp_helpindex @objname = N'{table_name}'") key, column = 0, 2 # 返回的三列:index_name, index_description, index_keys 4. 在table_data_schema方法中: elif self.valves.db_type == "mssql": query = text( "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, '', '' " # 用空字符串代替主键和注释 "FROM INFORMATION_SCHEMA.COLUMNS " "WHERE TABLE_NAME = :table_name;" ) 然后,在展示列信息时,由于column_key和column_comment都是空,所以不会显示主键和注释。 但是,我们注意到在table_data_schema方法中,对于每个列,我们检查了column_key是否为"PRI"(主键)。在mssql分支中,我们返回的column_key是空字符串,所以不会标记主键。 为了标记主键,我们可以单独查询主键信息,然后标记。这里我们暂时不实现。 最后,由于我们添加了新的数据库类型,在Valves模型的db_type字段的描述中,应该包含mssql。但是原描述已经包含“e.g.”,所以可以不用改。 另外,注意在Valves中,db_port的默认值是3306(MySQL的端口),而SQL Server默认是1433。所以用户需要自行设置端口。 由于代码修改较多,我们重新输出整个修改后的代码。注意,我们只修改了四个方法(添加了mssql分支),其他地方不变。 注意:在get_table_indexes方法中,对于mssql,我们使用了字符串拼接,这可能有SQL注入风险,但考虑到表名是工具内部传递的(由list_all_tables返回或用户通过参数传入,且已经存在),所以风险较低。 修改后的完整代码:</think>要将上述工具连接到 Microsoft SQL Server,需要进行以下关键修改: ### 需要添加的依赖 ```python requirements: pymysql, sqlalchemy, cx_Oracle, pyodbc # 新增 pyodbc ``` ### 代码修改方案 1. **在 `_get_engine()` 方法中添加 SQL Server 支持** ```python def _get_engine(self) -> Engine: if self.valves.db_type == "mssql": # 新增 SQL Server 分支 db_url = ( f"mssql+pyodbc://{self.valves.db_user}:{self.valves.db_password}" f"@{self.valves.db_host}:{self.valves.db_port}/{self.valves.db_name}" "?driver=ODBC+Driver+17+for+SQL+Server" ) elif self.valves.db_type == "mysql": ... ``` 2. **在 `list_all_tables()` 中添加 SQL Server 支持** ```python def list_all_tables(self, db_name: str) -> str: ... elif self.valves.db_type == "mssql": # 新增 result = conn.execute(text( "SELECT table_name FROM information_schema.tables " "WHERE table_type = 'BASE TABLE'" )) ... ``` 3. **在 `get_table_indexes()` 中添加 SQL Server 支持** ```python def get_table_indexes(self, db_name: str, table_name: str) -> str: ... elif self.valves.db_type == "mssql": # 新增 query = text(""" SELECT i.name AS index_name, c.name AS column_name FROM sys.indexes i JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id WHERE i.object_id = OBJECT_ID(:table_name) """) key, column = 0, 1 # 索引名和列名 ... ``` 4. **在 `table_data_schema()` 中添加 SQL Server 支持** ```python def table_data_schema(self, db_name: str, table_name: str) -> str: ... elif self.valves.db_type == "mssql": # 新增 query = text(""" SELECT c.name AS column_name, t.name AS data_type, c.is_nullable, ISNULL(( SELECT 'PRIMARY KEY' FROM sys.key_constraints kc JOIN sys.index_columns ic ON kc.parent_object_id = ic.object_id WHERE kc.type = 'PK' AND ic.column_id = c.column_id AND ic.object_id = c.object_id ), '') AS column_key, ep.value AS column_comment FROM sys.columns c JOIN sys.types t ON c.user_type_id = t.user_type_id LEFT JOIN sys.extended_properties ep ON c.object_id = ep.major_id AND c.column_id = ep.minor_id WHERE c.object_id = OBJECT_ID(:table_name) """) ... ``` ### 关键修改说明 1. **驱动选择**:使用 `pyodbc` + `ODBC Driver 17 for SQL Server`(需在目标系统安装) 2. **连接字符串**:`mssql+pyodbc://` 格式包含认证信息和数据库名称 3. **系统表查询**: - 表列表:`information_schema.tables` - 索引信息:`sys.indexes` 和 `sys.index_columns` - 表结构:`sys.columns` 结合 `sys.types` 和 `sys.extended_properties` 4. **主键检测**:通过 `sys.key_constraints` 识别主键列 5. **注释获取**:从 `sys.extended_properties` 获取列注释 ### 使用示例 ```python # 配置 SQL Server 连接 tool.valves.db_type = "mssql" tool.valves.db_host = "sqlserver.example.com" tool.valves.db_port = 1433 tool.valves.db_name = "AdventureWorks" tool.valves.db_user = "sa" tool.valves.db_password = "your_strong_password" # 获取所有表 print(tool.list_all_tables("AdventureWorks")) # 获取表结构 print(tool.table_data_schema("AdventureWorks", "Employees")) ``` ### 注意事项 1. 需在服务器安装 ODBC Driver 17 for SQL Server 2. 防火墙需开放 1433 端口(默认) 3. SQL Server 需启用混合认证模式 4. 对于 Azure SQL 需调整连接字符串格式
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值