为数据库创建一个新表

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

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();

        }

posted @ 2012-07-23 17:47  smodi  阅读(2811)  评论(0编辑  收藏  举报