Create table命令并不实际创建表c#

本文关键字:创建 不实际 table 命令 Create | 更新日期: 2023-09-27 18:11:21

我试图创建一个命令,应该根据名称创建一个表,输入在一个文本框中。没有错误,工作,查询看起来不错,但实际上并没有创建表。为什么呢?

private void button1_Click(object sender, EventArgs e)
{
    int count = 0;
    var connString = (@"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + @"'Grupe.sdf");
    using (var conn = new SqlCeConnection(connString))
    {
        try
        {
            conn.Open();
            var query = "CREATE TABLE "  + textBox1.Text.Trim() + "(" + "Id int NOT NULL IDENTITY (1,1) PRIMARY KEY" ;
            MessageBox.Show(query);
            foreach (Control c in this.Controls)
            {
                if (c.Name.Contains("temp") && c is TextBox)
                {
                    if (!String.IsNullOrEmpty(c.Text))
                    {
                        query += "," + c.Text.Trim() + " nvarchar(MAX) NULL";
                        count++;
                    }
                }
            }
            query += ")";
            var command = new SqlCeCommand(query, conn);
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}

Create table命令并不实际创建表c#

试试

    MessageBox.Show(query);

之前
    var command = new SqlCeCommand(query, conn);

你肯定会发现一个语法错误。代码似乎很好,但我猜你必须看到完整的生成查询创建表。

我相信nvarchar是有4000个字符限制的东西,我找不到nvarchar是支持的类型列表。使用ntext在你的代码中工作得很好。

private void button1_Click(object sender, EventArgs e)
    {
        int count = 0;
        var connString = (@"Data Source=Grupe.sdf");
        if (!File.Exists("Grupe.sdf"))
        {
            SqlCeEngine engine = new SqlCeEngine(connString);
            engine.CreateDatabase();
        }
        using (var conn = new SqlCeConnection(connString))
        {
            try
            {
                conn.Open();
                var query = "CREATE TABLE " + textBox1.Text.Trim() + "(" + "Id int NOT NULL IDENTITY (1,1) PRIMARY KEY";
                MessageBox.Show(query);
                foreach (Control c in this.Controls)
                {
                    if (c.Name.Contains("temp") && c is TextBox)
                    {
                        if (!String.IsNullOrEmpty(c.Text))
                        {
                            query += "," + c.Text.Trim() + " ntext NULL";

                            count++;
                        }
                    }

                }
                query += ")";
                MessageBox.Show(query);
                var command = new SqlCeCommand(query, conn);
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }

在bin/debug文件夹中查找数据库文件的副本!