RT,本人是初学者,现在有个问题,请问下高手,要做个数据库应用,创建好的表单,有若干个文本框输入。在文本框里输入的作为在数据库里新创建表的字段。以后这个表可以继续用来存取和更新数据。要如何做?高手提示下,指点下。不胜感激!

解决方案 »

  1.   

    把创建表的sql给写好,在查询分析器里运行没有问题,然后在程序里直接执行它就可以了
    string tableName=this.textBox1.Text; 
    string add_table="create table " + tableName + " (num NVarChar(16) not null primary key)";  
    SqlCommand comm=new SqlCommand(add_table,conn);  
    comm.CommandType= CommandType.Text; 
    comm.Connection.Open();  
    comm.ExecuteNonQuery();  
    conn.Close(); 
    comm.Dispose(); 
      

  2.   


    就是把文本框输入的内容拼凑成SQL语句。
      

  3.   

    构造创建数据表的SQL语句就可以了,然后执行它。
    下面的代码的表结构在DataTable中,楼主把那个循环替换成需要的就可以private void TableCheck()
        {
            // Create an OleDb database connection using the connection string
            // provided when the web form is submitted
            OleDbConnection oledbConn = new OleDbConnection(textBoxOleDb.Text);
            try
            {
                // Open the database connection
                oledbConn.Open();
                // Retrieve database schema information for only the table we are looking for
                // In this example the table name is the name of the XML file without the extension
                DataTable schemaTable = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
                    new object[] { null, null, tableName, "TABLE" });
                String sqlCmd = "";
                // Check to see if the table exists in the database schema
                // If the table exists in the schema there will be 1 row in the DataTable
                // If the table does not exist in the schema the DataTable row count will be zero
                if (schemaTable.Rows.Count < 1)
                {
                    // Make the create table sql command by iterating through the XML file's
                    // columns. This way the database columns will have the same name as the XML file.
                    sqlCmd = "create table " + tableName + " (";
                    for (int i = 0; i < dataTableXml.Columns.Count; i++)
                    {
                        // This adds each column as a text/string type with a length of 100
                        sqlCmd = sqlCmd + dataTableXml.Columns[i].ColumnName.ToString() + " char(100),";
                    }
                    // Remove the last ","
                    sqlCmd = sqlCmd.Substring(0, sqlCmd.Length - 1) + ");";
                    // Create and execute the create table command
                    OleDbCommand oledbCmd = new OleDbCommand(sqlCmd, oledbConn);
                    oledbCmd.ExecuteNonQuery();
                }
            }
            catch
            {
                // If there are errors you will get this message
                Message.Text = "The table could not be created or database does not exist.";
            }
            finally
            {
                // Close the database connection
                oledbConn.Close();
            }
        }