我正在尝试创建一个命令,该命令应根据名称在textBox中键入创建表。没有错误,工作,查询看起来不错,但实际上并没有创建表。那是为什么?
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());
}
}
}
答案 0 :(得分:0)
尝试
MessageBox.Show(query);
前
var command = new SqlCeCommand(query, conn);
您肯定会发现语法错误。代码似乎没问题,但我想你必须看到完整的生成查询for create table。
我相信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());
}
}
}
答案 1 :(得分:0)
在bin / debug文件夹中查找数据库文件的副本!