Create table at run time in Database by using ASP.NET


Using the following code you can easily create a new table in a Database and fill records in that table. You can use this code on the Page_Load or in any Button click event.

try

{

    if (!(conn.State == ConnectionState.Open))

    {

        conn.Open();

    }

    string sql = "CREATE TABLE mySchoolRecord" + "
    (StudentId INTEGER CONSTRAINT PkeyMyId PRIMARY KEY,"
   
+ "Name CHAR(50), Address CHAR(255), Contact INTEGER)";

    cmd = new OdbcCommand(sql, conn);

    cmd.ExecuteNonQuery();

 

    sql = "INSERT INTO mySchoolRecord (StudentId, Name,

    Address,Contact) " + "VALUES (1, 'Mr. Manish', "

    + " 'Sector-12,Noida', 2447658 ) "

    cmd = new OdbcCommand(sql, conn);

    cmd.ExecuteNonQuery();

 

    sql = "INSERT INTO mySchoolRecord (StudentId, Name,

    Address,Contact) " + "VALUES (2, 'Mr. Ravi', "

    + " 'New Delhi', 2584076521 ) "

    cmd = new OdbcCommand(sql, conn);

    cmd.ExecuteNonQuery();

 

    sql = "INSERT INTO mySchoolRecord (StudentId, Name,

    Address,Contact) " + "VALUES (3, 'Mr. Peter', "

    + " 'United States', 25684124 ) "

    cmd = new OdbcCommand(sql, conn);

    cmd.ExecuteNonQuery();

 

 

    if (conn.State == ConnectionState.Open)

    {

        conn.Close();

    }

}

catch (OdbcException ex)

{

    MessageBox.Show(ex.Message.ToString);

}


Similar Articles