创建表并插入一个不起作用的命令

时间:2017-11-24 15:48:05

标签: c# c#-4.0 sqlite

我有这个C#代码来执行SqLite命令:

 using (var conn = new SQLiteConnection(localPath, true))
            {
                SQLiteCommand command = new SQLiteCommand(conn);
                command.CommandText = query;
                command.ExecuteNonQuery();
            }

当我用C#代码运行这个SQL时,我有空表:

 CREATE TABLE [MyEmailList] (
      [MyEmailListId]  INTEGER PRIMARY KEY ASC AUTOINCREMENT 
    ,[FirstName]  TEXT 
    ,[LastName]  TEXT 
    ,[Email]  TEXT 
    ,[Link]  TEXT 
    );


     INSERT INTO [MyEmailList] ( [FirstName],[LastName],[Email],[Link]) VALUES 
('SomeFirstName2','SomeLastname2','SomeEmail2@host.com','http://mywebsite.com/link2.htm')
    ,('SomeFirstName3','SomeLastname3','SomeEmail3@host.com','http://mywebsite.com/link3.htm')
    ,('SomeFirstName4','SomeLastname4','SomeEmail4@host.com','http://mywebsite.com/link4.htm')
    ,('SomeFirstName5','SomeLastname5','SomeEmail5@host.com','http://mywebsite.com/link5.htm');

所以看起来表已经创建了但是插入部分脚本没有运行。 当我运行create table并插入到单独的命令中时,它可以工作。

有没有办法运行create table并插入一个命令?

UPD:我已尝试过连接并将GO包含在SQL语句中,仍然无法正常工作。

    using (var conn = new SQLiteConnection(localPath, true))
            {

                var q1 = @" CREATE TABLE [MyEmailList] (
      [MyEmailListId]  INTEGER PRIMARY KEY ASC AUTOINCREMENT 
    ,[FirstName]  TEXT 
    ,[LastName]  TEXT 
    ,[Email]  TEXT 
    ,[Link]  TEXT 
    );
    GO;

     INSERT INTO [MyEmailList] ( [FirstName],[LastName],[Email],[Link]) VALUES 
('SomeFirstName2','SomeLastname2','SomeEmail2@host.com','http://mywebsite.com/link2.htm')
    ,('SomeFirstName3','SomeLastname3','SomeEmail3@host.com','http://mywebsite.com/link3.htm')
    ,('SomeFirstName4','SomeLastname4','SomeEmail4@host.com','http://mywebsite.com/link4.htm')
    ,('SomeFirstName5','SomeLastname5','SomeEmail5@host.com','http://mywebsite.com/link5.htm');
GO;
";

                conn.Execute(q1);
                conn.Commit();
                conn.Close();

            }

1 个答案:

答案 0 :(得分:0)

您可以在创建表格后调用command.ExecuteNonQuery();,然后在插入后再次调用。

  command.CommandText = " CREATE TABLE [MyEmailList] (
      [MyEmailListId]  INTEGER PRIMARY KEY ASC AUTOINCREMENT 
    ,[FirstName]  TEXT 
    ,[LastName]  TEXT 
    ,[Email]  TEXT 
    ,[Link]  TEXT 
    );";
    command.ExecuteNonQuery();
    command.CommandText = " INSERT INTO [MyEmailList] ( [FirstName],[LastName],[Email],[Link]) VALUES 
('SomeFirstName2','SomeLastname2','SomeEmail2@host.com','http://mywebsite.com/link2.htm')
    ,('SomeFirstName3','SomeLastname3','SomeEmail3@host.com','http://mywebsite.com/link3.htm')
    ,('SomeFirstName4','SomeLastname4','SomeEmail4@host.com','http://mywebsite.com/link4.htm')
    ,('SomeFirstName5','SomeLastname5','SomeEmail5@host.com','http://mywebsite.com/link5.htm');";
    command.ExecuteNonQuery();

您还可以添加一项检查以查看该表是否已存在。

 var myEmailList = command.ExecuteNonQuery();
 if (name != null && name.ToString() == "MyEmailList")
        return;