1

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?

1

1 Answer 1

8

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Do you mean that you want to execute the SQL using C#?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.