2012-11-12 38 views
1

與我的代碼我可以創建一個sqlite數據庫文件。用c#創建sqlite數據庫通過使用外部ramin.sql文件

public static void sqlite(string sqlite_file) 
    { 
     SQLiteConnection.CreateFile(sqlite_file); 
     string str = "CREATE TABLE IF NOT EXISTS `aliases` (`key` varchar(255) NOT NULL,`value` varchar(255) NOT NULL);.... "   
     SQLiteConnection connection = new SQLiteConnection { 
      ConnectionString = "Data Source=" + sqlite_file 
     }; 
     connection.Open(); 
     SQLiteCommand command = new SQLiteCommand(connection) { 
      CommandText = str 
     }; 
     command.ExecuteNonQuery(); 
     command.Dispose(); 
     connection.Close(); 
     connection.Dispose(); 
    } 

所以我的問題: 我想創建一個由像C外部SQL文件的讀取數據的數據庫://mysql/ramin.sql 什麼樣的變化,我必須在我的代碼做?在ramin.sql文件

和數據格式是:

CREATE TABLE IF NOT EXISTS `aliases` (`key` varchar(255) NOT NULL,`value` varchar(255) NOT NULL); 
CREATE TABLE IF NOT EXISTS `badnames` (`badname` varchar(255) NOT NULL); 
CREATE TABLE IF NOT EXISTS `badwords` (`badword` varchar(255) NOT NULL); 
and evey command in every line... 
+0

你可以得到在此基礎上[文章]一個想法(http://stackoverflow.com/questions/2049109/how-to -import-SQL - 進入 - sqlite3的) – bonCodigo

回答

0

打開.sql文件爲文本文件,讀取每一行,並把它插入到一個SQLiteCommand

0

您可以使用設置在CommmandText所有SQL文本System.IO.File.ReadAllText

SQLiteCommand command = new SQLiteCommand(connection); 
command.CommandText = System.IO.File.ReadAllText(@"file.sql"); 
0
privat string _dataSource = @"H:\Ik.db"; 
private SQLiteConnection _connection; 
private SQLiteCommand _command; 

private void connectToSQLite() 
{ 
    using (SQLiteConnection _connection = new SQLiteConnection()) 
    { 
     if (File.Exists(@"H:\Ik.db")) 
     { 
      _connection.ConnectionString = $"Data Source={_dataSource};Version=3"; 
      _connection.Open(); 
      using (SQLiteCommand _command = new SQLiteCommand()) 
      { 
       _command.Connection = _connection; 
        _command.CommandText = "INSERT INTO Customer(id, Lastname,firstname,Code,City) " + 
        $"VALUES(NULL, '{txt_Lastname.Text}', '{txt_name.Text}', '{ txt_code.Text}', '{ txt_city.Text}')"; 
       try 
       { 
        _command.ExecuteNonQuery(); 
        MessageBox.Show($"You Connected to local Data Base under {_dataSource} Sucssefuly"); 
       } 
       catch (Exception) 
       { 

        throw; 
       } 
      } 
     } 
     else 
     { 
      SQLiteConnection.CreateFile(@"H:\Ik.db"); 

     } 
    } 
} 
相關問題