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

来源:互联网 发布:网络阅读的利与弊 编辑:程序博客网 时间:2024/05/22 00:37

【转载于博客】如何用C#为SQL Server数据库创建一个新表?


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

1.       我们可以用 ADO.NET 写出并执行 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-sharpcorner.com/UploadFile/mahesh/CreatingDBProgrammaticallyMCB11282005064852AM/CreatingDBProgrammaticallyMCB.aspx
http://social.msdn.microsoft.com/Forums/en/adodotnetdataproviders/thread/4929a0a8-0137-45f6-86e8-d11e220048c3
http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/ed6e07c6-1876-43cd-9bd4-f69dc22a7d58
0 0