简体   繁体   中英

C# creating a table and inserting rows in to SQL Server 2008

Here's my connection string:

// Initialize a connection string    
string myConnectionString = 
   "Provider=SQLOLEDB;Data Source=hermes;Initial Catalog=qcvaluestest;
    Integrated Security=SSPI;";

How would I create a table in the database and insert rows into it?

Create table example:

CREATE TABLE MyTable
(
   Id  int IDENTITY(1,1) PRIMARY KEY CLUSTERED,
   Name        varchar(50) 
)

Insert records:

Insert INTO MyTable Values ("Abe")

You should think carefully before letting an application modify your DB structure though...

Alternatively you can use SQL Server Management Objects . Here is a good link that goes over using SSMO to create a table:

http://www.davidhayden.com/blog/dave/archive/2006/01/27/2775.aspx

UPDATE Your C# would look like this:

string queryString = 
    @"
CREATE TABLE MyTable
(
   Id  int IDENTITY(1,1) PRIMARY KEY CLUSTERED,
   Name        varchar(50) 
)";

using (SqlConnection connection = new SqlConnection(
           myConnectionString ))
{
    SqlCommand command = new SqlCommand(
        queryString, connection);
    connection.Open();
    command.ExecuteNonReader();
    command.CommandText = @"Insert INTO MyTable Values ('Abe')";
    command.ExecuteNonReader();
}

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