简体   繁体   中英

Programmatically, how can I specify the database in which I want to put my table C#

I just wanted to know: Using C#, how can I specify in which database a want to put my table? Here is what I am doing:

 str2 = "CREATE TABLE maTable4" +
            "(" +
            "Prenom DECIMAL(3)," 
            "Nom varchar(20)," +
            "Famille varchar(20)," +
            ");";
            SqlCommand maCommande = new SqlCommand(str2, myConn);
            try
            {
                myConn.Open();
                maCommande.ExecuteNonQuery();
                myConn.Close();
            }
            catch
            {
                myConn.Close();
                Console.WriteLine("table created ");
            }

As you can see, this table goes no where.

You can use a three-segment identifier for your table. Otherwise, it will be created to the default database you're logged in to, on the login's default schema.

str2 = "CREATE TABLE DatabaseName.SchemaName.TableName" + // rest of the code...

I'm not sure but you may use one trick

Create connection string Dynamically

string connetionString = null;
string ServerName="Your server";
string DatabaseName="Your database";
string UserName="UserName";
string Password="Password";

connetionString =String.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3}",ServerName,DatabaseName,UserName,Password);

SqlConnection myConn=new SqlConnection(connetionString);
.
.
.
// rest your code...            

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM