1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 如何用C#为SQL Server数据库创建一个新表?

如何用C#为SQL Server数据库创建一个新表?

时间:2022-05-07 14:04:09

相关推荐

如何用C#为SQL Server数据库创建一个新表?

有两种方法来为数据库创建一个新表,

1.我们可以用写出并执行T-SQL语句来创建表:

private void CreateTableBtn_Click(object sender, System.EventArgs e)

{

//打开连接

if (conn.State == ConnectionState.Open)

conn.Close();

ConnectionString = "Integrated Security=SSPI;" +

"Initial Catalog=mydb;" +

"Data Source=localhost;";

conn.ConnectionString = ConnectionString;

conn.Open();

sql = "CREATE TABLE myTable" +

"(myId INTEGER CONSTRAINT PKeyMyId PRIMARY KEY," +

"myName CHAR(50), myAddress CHAR(255), myBalance FLOAT)";

cmd = new SqlCommand(sql, conn);

cmd.ExecuteNonQuery();

}

2.我们可以引用SMO库并用SMO函数来创建一个表

private void CreateTableBtn_Click(object sender, System.EventArgs e)

{

// 建立数据库服务器

string connectionString = "...";

SqlConnection connection =

new SqlConnection(connectionString);

Server server =

new Server(new ServerConnection(connection));

// 在我的个人数据库中创建表

Database db = server.Databases["mydb"];

// 建立TestTable的新表

Table newTable = new Table(db, "TestTable");

// 添加主键ID列

Column idColumn = new Column(newTable, "ID");

idColumn.DataType = DataType.Int;

idColumn.Nullable = false;

idColumn.Identity = true;

idColumn.IdentitySeed = 1;

idColumn.IdentityIncrement = 1;

// 添加"Title"列

Column titleColumn = new Column(newTable, "Title");

titleColumn.DataType = DataType.VarChar(50);

titleColumn.Nullable = false;

// 为 Table对象添加列

newTable.Columns.Add(idColumn);

newTable.Columns.Add(titleColumn);

// 为表创建一个主键的索引

Index index = new Index(newTable, "PK_TestTable");

index.IndexKeyType = IndexKeyType.DriPrimaryKey;

// 主键索引包括1列 "ID"

index.IndexedColumns.Add(new IndexedColumn(index, "ID"));

//表中添加一个新的索引.

newTable.Indexes.Add(index);

// 在数据库中实际创建一个表

newTable.Create();

}

相关帖子:

http://www.c-/UploadFile/mahesh/CreatingDBProgrammaticallyMCB1128064852AM/CreatingDBProgrammaticallyMCB.aspx

http://social./Forums/en/adodotnetdataproviders/thread/4929a0a8-0137-45f6-86e8-d11e28c3

http://social./Forums/en-US/adodotnetdataproviders/thread/ed6e07c6-1876-43cd-9bd4-f69dc22a7d58

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。