Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Using c# code, I have to check whether a database exists or not first and if it doesn't exists I have to create the database. And once DB exists then I need to create few tables using the c# code itself.

Please reply.

Thanks & Regards,
Mathi.
Posted
Comments
Ron Beyer 10-Oct-13 22:58pm    
Alright, so what is your question? I see a lot of what you want to do, which is great, but nothing asking specific help. You also need to specify what database you are using.
Sushil Mate 10-Oct-13 23:38pm    

Hi,

Please check this.

Please change the bolded text

C#
string sqlCreateDBQuery;
    try
    {
        SqlConnection tmpConn = new SqlConnection("server=(local)\\SQLEXPRESS;Trusted_Connection=yes");

        sqlCreateDBQuery = "SELECT * FROM master.dbo.sysdatabases where name =
        \'Your db name\'";

        using (tmpConn)
        {
            tmpConn.Open();
            tmpConn.ChangeDatabase("master");

            using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
            {
                int exists = sqlCmd.ExecuteNonQuery();

                if (exists <= 0)
                {
                   string script = your db creating sql script;
                   sqlCmd.ExecuteNonQuery(script);
                }
                else
                {
                   string script = your tables creating sql script;
                   sqlCmd.ExecuteNonQuery(script);
                }
            }
        }
    }
    catch (Exception ex) { }
 
Share this answer
 
Comments
Mathi2code 11-Oct-13 3:24am    
Hi Renju,

When I use this particular code I'm getting an error saying "Create Database Access denied from MASTER database". Do I need to do something else.
Renju Vinod 11-Oct-13 5:37am    
Hi Mathi2code,

Change the connection string with UId and pwd which having permission for creating database.
Mathi2code 13-Oct-13 23:26pm    
ok.. Actually I tried giving sa login. But it failed. Then I got to know that the sa login is disabled. And it worked fine when I created with another login.
Thanks a lot Renju.

With Regards,
Mathi
 
Share this answer
 
like this

your connection string is like conn

C#
sqlcommand cmd = sqlcommand("create database your name",conn); 

conn.open();

cmd.excutenonquery();


it will automatically through error if database is already exists

and if database is not there it will create database.

same procedure for create tables also.

if any issue ask again.
 
Share this answer
 
Plz provide the needfull information so the solution can be provided.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900