使用外部ramin.sql文件使用c#创建sqlite数据库

时间:2012-11-12 23:43:08

标签: c# sql sqlite

使用我的代码,我可以创建一个sqlite数据库文件。

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();
    }

所以我的问题: 我想创建一个数据库,从外部sql文件读取数据,如c://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...

3 个答案:

答案 0 :(得分:0)

将.sql文件作为文本文件打开,读取每一行,并将其插入SQLiteCommand

答案 1 :(得分:0)

您可以使用CommmandText

System.IO.File.ReadAllText中设置所有sql文本
SQLiteCommand command = new SQLiteCommand(connection);  
command.CommandText = System.IO.File.ReadAllText(@"file.sql");  

答案 2 :(得分: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");

        }
    }
}