Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3352576
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T02:02:49+00:00 2026-05-18T02:02:49+00:00

My need is to write a code, which creates a db creates four tables

  • 0

My need is to write a code, which

  • creates a db
  • creates four tables
  • creates primary keys
  • creates foreign keys
  • and constraints like type int or boolean or string etc

Yes I know w3c shools has the sql codes, but the problem is I first need to detect if these things exists or not one by one.

And this is for me a great problem.

I tried to work with sql exceptions, but it does not provide way to categorize the exceptions –like databasethereexception–tablealreadythereEXCEPTION..

So please provide some coded examples or links for the above purpose,

note: yes I can google, but it is full full full of examples and codes, it gets too confusing, so hoping for straight professional examples please

Also a sample of the type of code i am working with

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class Making_DB : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //check or make the db
        MakeDB();
        CheckDB();
    }

    public void CheckDB()
    {
        try
        {
            string Data_source = @"Data Source=A-63A9D4D7E7834\SECOND;";
            string Initial_Catalog = @"Initial Catalog=master;";
            string User = @"User ID=sa;";
            string Password = @"Password=two";

            string full_con = Data_source + Initial_Catalog + User + Password;

            SqlConnection connection = new SqlConnection(full_con);

            connection.Open();

            SqlDataAdapter DBcreatingAdaptor = new SqlDataAdapter();
            DataSet ds2 = new DataSet();
            SqlCommand CheckDB = new SqlCommand("select * from sys.databases where name = 'my_db'", connection);
            DBcreatingAdaptor.SelectCommand = CheckDB;
            DBcreatingAdaptor.Fill(ds2);
            GridView1.DataSource = ds2;
            GridView1.DataBind();   // do not forget this//
            Response.Write("<br />WORKING(shows zero if db not there) checking by gridview rows: " + GridView1.Rows.Count.ToString());
            Response.Write("<br />NOT WORKING(keeps on showing one always!) checking by dataset tables: " + ds2.Tables.Count.ToString());
            DBcreatingAdaptor.Dispose();
            connection.Close();

            //Inaccesible due to protection level. Why??
            //SqlDataReader reader = new SqlDataReader(CheckDB, CommandBehavior.Default);
        }//try
        catch (Exception e)
        {
            Response.Write("   checking::    " +  e.Message);
        }//catch
    }//check db

    public void MakeDB()
    {
        try
        {
            string Data_source = @"Data Source=A-63A9D4D7E7834\SECOND;";
            //string Initial_Catalog = @"Initial Catalog=replicate;";
            string User = @"User ID=sa;";
            string Password = @"Password=two";

            string full_con = Data_source + User + Password;

            SqlConnection connection = new SqlConnection(full_con);

            connection.Open();

            //SqlCommand numberofrecords = new SqlCommand("SELECT COUNT(*) FROM dbo.Table_1", connection);
            SqlCommand CreateDB = new SqlCommand("CREATE DATABASE my_db", connection);

            //DataSet ds2 = new DataSet();

            SqlDataAdapter DBcreatingAdaptor = new SqlDataAdapter();
            DBcreatingAdaptor.SelectCommand = CreateDB;
            DBcreatingAdaptor.SelectCommand.ExecuteNonQuery();

            //check for existance
            //select * from sys.databases where name = 'my_db'

            DataSet ds2 = new DataSet();
            SqlCommand CheckDB = new SqlCommand(" select * from sys.databases where name = 'my_db'", connection);
            DBcreatingAdaptor.SelectCommand = CheckDB;
            //DBcreatingAdaptor.SelectCommand.ExecuteReader();
            DBcreatingAdaptor.Fill(ds2);
            GridView1.DataSource = ds2;

            //if not make it
        }//try
        catch (Exception e)
        {
            Response.Write("<br /> createing db error:  " + e.Message);
        }//catch
    }//make db
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T02:02:49+00:00Added an answer on May 18, 2026 at 2:02 am

    As I’ve already mentioned in my comment – I would NEVER write out directly to the Response stream from a function like this! Pass back a string with an error message or something – but do NOT write out to the stream or screen directly.

    You should use the best practice of wrapping SqlConnection and SqlCommand into using(...){.....} blocks to make sure they get properly disposed. Also, populating a gridview from within this code is really bad – you’re mixing database access (backend) code and UI frontend code – really really bad choice. Why can’t you just pass back the data table and then bind it in the UI front end code to the grid??

    public DataTable CheckDB()
    {
        DataTable result = new DataTable();
    
        try
        {
            string connectionString = 
              string.Format("server={0};database={1};user id={2};pwd={3}"
                            "A-63A9D4D7E7834\SECOND", "master", "sa", "two"); 
    
            string checkQuery = "SELECT * FROM sys.databases WHERE name = 'my_db'";
    
            using(SqlConnection _con = new SqlConnection(connectionString))
            using(SqlCommand _cmd = new SqlCommand(checkQuery, _con))
            {
                SqlDataAdapter DBcreatingAdaptor = new SqlDataAdapter(_cmd);
                DBcreatingAdaptor.Fill(_result);
            }
        }//try
        catch (SqlException e)
        {
             // you can inspect the SqlException.Errors collection and 
             // get **VERY** detailed description of what went wrong,
             // including explicit SQL Server error codes which are 
             // unique to each error
        }//catch
    
        return result;
    }//check db
    

    Also – you’re doing the MakeDB() method way too complicated – why a table adapter?? All you need is a SqlCommand to execute your SQL command – you already have a method that checks that a database exists.

    public void MakeDB()
    {
        try
        {
            string connectionString = 
              string.Format("server={0};database={1};user id={2};pwd={3}"
                            "A-63A9D4D7E7834\SECOND", "master", "sa", "two"); 
    
            string createDBQuery = "CREATE DATABASE my_db";
    
            using(SqlConnection _con = new SqlConnection(connectionString))
            using(SqlCommand _cmd = new SqlCommand(createDBQuery, _con))
            { 
                _con.Open();
                _cmd.ExecuteNonQuery();
                _con.Close();
            }
        }//try
        catch (SqlException e)
        {
           // check the detailed errors 
           // error.Number = 1801 : "database already exists" (choose another name)
           // error.Number = 102: invalid syntax (probably invalid db name)
           foreach (SqlError error in e.Errors)
           {
              string msg = string.Format("{0}/{1}: {2}", error.Number, error.Class, error.Message);
           }
        }//catch
    }//make db
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need write an update statement that used multiple tables to determine which rows
I need to write code that picks up PGP-encrypted files from an FTP location
I need to write robust code in .NET to enable a windows service (server
I need to write the code that would format the value according to the
I've got a bunch of legacy code that I need to write unit tests
This code does not seem to compile, I just need to write something to
I need to write a Delphi application that pulls entries up from various tables
I've got the following bit of code (that another developer wrote) that I need
I need to write a program used internally where different users will have different
I need to write a Java Comparator class that compares Strings, however with one

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.