C # How to dynamically create SQL database tables using asp. net

Source: Internet
Author: User

Copy codeThe Code is as follows: // a required namespace
Using System;
Using System. Data;
Using System. Data. SqlClient;
// The general content in the middle is omitted
String tabName = "table1 ";
// Declare the name of the table to be created. You can also retrieve it from textbox;
String sqlStr = "create table ";
SqlStr + = tabName + "(";
SqlStr + = "col0 numeric identity (1, 1) primary key ,";
// Col0 is the column name, which can also be obtained from textbox.
// Identity () indicates the incrementing seed.
// Primary key defines the primary key
SqlStr + = "col1 varchar (20 ),";
SqlStr + = "col2 smalldatetime ,";
SqlStr + = "col3 varchar (20 ),";
SqlStr + = "col4 int ,";
SqlStr + = "col5 varchar (20 ),";
SqlStr + = ")";

// Instantiate the SQL connection
SqlConnection conn = new SqlConnection ("server =.; database = dbName; uid = sa; pwd = sa ");
Conn. Open ();
// Instantiate an SQL command
SqlCommand cmd = new SqlCommand (sqlStr, conn );
// Execute the SQL command
Cmd. ExecuteNonQuery ();
// Close the connection
Conn. Close ();

My code:Copy codeThe Code is as follows: string tabName = "Job ";
String sqlStr = "create table ";
SqlStr + = tabName + "(";
SqlStr + = "Id int identity (1, 1) primary key ,";
// Col0 is the column name, which can also be obtained from textbox.
// Identity () indicates the incrementing seed.
// Primary key defines the primary key

SqlStr + = "num int ,";
SqlStr + = "Colour varchar (50 ),";

SqlStr + = "Other varchar (50 ),";
SqlStr + = ")";

// Instantiate the SQL connection
String sss = "Data Source = (local); Initial Catalog =" + dataconnect + "; Integrated Security = True ";
SqlConnection conn = new SqlConnection (sss );
Conn. Open ();

// Instantiate an SQL command
SqlCommand cmd = new SqlCommand (sqlStr, conn );

// Execute the SQL command
Cmd. ExecuteNonQuery ();

// Close the connection
Conn. Close ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.