在创建表查询时如果EXISTS

时间:2012-06-21 21:43:55

标签: c# sqlite

我需要编写q查询,我检查表是否存在,如果存在,我需要在那里插入值。我总是得到编译错误,因为我的语法错误。驾驶室有人请指出正确的代码吗?欣赏它

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
        createDataBase();
        createDataTable();
    }

    private void createDataBase()
    {
       SQLiteDataAdapter  dataBase = new SQLiteDataAdapter();
    }


    private SQLiteConnection getConnection() 
    { 
        return new SQLiteConnection("Data Source=file1.db"); 
    }


    private void ExecuteQuery(string txtQuery)
    {            
     using (SQLiteConnection sqlcon =  getConnection())
     {
            using (SQLiteCommand sqlcmd = sqlcon.CreateCommand())
            {
                sqlcmd.CommandText = txtQuery;
                sqlcon.Open();
                sqlcmd.ExecuteNonQuery();
            }
        }
    }


    private void createDataTable()
    {
        //ExecuteQuery("DROP TABLE IF EXISTS 'RECORDS'");
        //ExecuteQuery("CREATE TABLE RECORDS ( ID varchar(255))");
        //ExecuteQuery("CREATE TABLE (IF NOT EXISTS) 'RECORDS'");
        //("IF (EXISTS (SELECT ID FROM sqlite_master WHERE NAME = 'RECORDS'))");
    }


    private void button1_Click(object sender, EventArgs e)
    {
          AddValue(textBox1.Text);  
        ////ExecuteQuery("IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA <> NULL AND TABLE_NAME = 'RECORDS')) BEGIN INSERT INTO RECORDS (ID) VALUES ('" + textBox1.Text + "')");    
    }


    private void AddValue(string value)
    {
      ExecuteQuery("INSERT INTO RECORDS (ID) VALUES ('" + value + "')");
    }
}

}

2 个答案:

答案 0 :(得分:1)

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'TheSchema' 
                 AND  TABLE_NAME = 'TheTable'))
BEGIN
    --your insert logic
END

答案 1 :(得分:1)

这是一个例子

  SQLiteCommand cmd = new SQLiteCommand();
  cmd.Connection = con;
  cmd.Connection.Open();
  cmd.CommandText = "SELECT name FROM sqlite_master WHERE name='MAIN'";
  SQLiteDataReader rdr = cmd.ExecuteReader();
  if (rdr.HasRows)
  {
        cmd.CommandText = "DROP TABLE 'MAIN'";
        cmd.ExecuteNonQuery();
  }

但这直接来自SQLite site

  SQLiteCommand cmd = new SQLiteCommand();
  cmd.Connection = con;
  cmd.CommandText = "DROP TABLE IF EXIST 'MAIN'";
  cmd.Connection.Open();
  cmd.ExecuteNonQuery();