开发者

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

Here's my connectio开发者_C百科n 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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜