MSSQL.create_table

MSSQL.create_table(table_name, column_specs, schema_name=None, verbose=False)[source]

Create a table.

Parameters:
  • table_name (str) – name of a table

  • column_specs (str) – specifications for each column of the table

  • schema_name (str | None) – name of a schema; when schema_name=None (default), it defaults to DEFAULT_SCHEMA (i.e. 'dbo')

  • verbose (bool | int) – whether to print relevant information in console, defaults to False

Examples:

>>> from pyhelpers.dbms import MSSQL

>>> testdb = MSSQL(database_name='testdb')
Creating a database: [testdb] ... Done.
Connecting <server_name>@localhost:1433/testdb ... Successfully.

>>> # Create a new table named 'test_table'
>>> tbl_name = 'test_table'
>>> col_spec = 'col_name_1 INT, col_name_2 varchar(255)'
>>> testdb.create_table(table_name=tbl_name, column_specs=col_spec, verbose=True)
Creating a table: [dbo].[test_table] ... Done.
>>> testdb.table_exists(table_name=tbl_name)
True
>>> testdb.get_column_names(table_name=tbl_name)
['col_name_1', 'col_name_2']
>>> test_tbl_col_info = testdb.get_column_info(table_name=tbl_name, as_dict=False)
>>> test_tbl_col_info.head()
                    column_0    column_1
TABLE_CATALOG         testdb      testdb
TABLE_SCHEMA             dbo         dbo
TABLE_NAME        test_table  test_table
COLUMN_NAME       col_name_1  col_name_2
ORDINAL_POSITION           1           2

>>> testdb.validate_column_names(table_name=tbl_name)
'"col_name_1", "col_name_2"'

>>> # Drop the table [dbo].[test_table]
>>> testdb.drop_table(table_name=tbl_name, verbose=True)
To drop the table [dbo].[test_table] from <server_name>@localhost:1433/testdb
? [No]|Yes: yes
Dropping [dbo].[test_table] ... Done.

>>> # Delete the database [testdb]
>>> testdb.drop_database(verbose=True)
To drop the database [testdb] from <server_name>@localhost:1433
? [No]|Yes: yes
Dropping [testdb] ... Done.