Имя источника данных SQLite 3 и Odbc

Уважать,

Как подключить базу данных sqlite из c # через строку подключения Odbc. Я хочу подключиться через имя источника данных, поэтому я не хочу использовать абсолютный путь для БД. Я создал ODBC DSN с именем источника данных «TestOdbc», а имя базы данных - это полный путь к моему sqlite test.db, который находится в C: \ Test \ test.db. В test.db есть одна таблица TestTable с несколькими записями.

Я пытаюсь использовать ODBCConnection в C # и SqliteConnection, но мне не повезло. С SqliteConnection я устанавливаю соединение, но соединение не было установлено с C: \ Test \ test.db. Я думаю, что новая база данных создается только в: memory, потому что, когда я пытаюсь выбрать записи из TestTable, я получил ошибку, что таблица не существует.

Пожалуйста, есть какие-нибудь предложения?

Код:

try
        {
            SQLiteConnection conn = new SQLiteConnection();
            conn.ConnectionString = "Driver=SQLite3 ODBC Driver;Datasource=TestOdbc;";
            conn.Open();

            SQLiteCommand comm = new SQLiteCommand();
            comm.Connection = conn;
            comm.CommandText = "SELECT * FROM TestTable";
            SQLiteDataReader created = comm.ExecuteReader();
            comm.Dispose();
            conn.Close();
            Console.WriteLine("connection opened!!!");
        }
        catch(SQLiteException ex)
        {

            Console.WriteLine(ex.Message);
        }
        catch(InvalidOperationException ex)
        {
            Console.WriteLine(ex.Message);
        }

person user2803095    schedule 13.09.2017    source источник


Ответы (1)


Попробуй это:

 //create table and insert data 

    private void button1_Click(object sender, EventArgs e)
            {
                // We use these three SQLite objects:
                SQLiteConnection conn;
                SQLiteCommand sqlite_cmd;
                SQLiteDataReader sqlite_datareader;

                // create a new database connection:
                conn = new SQLiteConnection("Driver = SQLite3 ODBC Driver; Datasource = TestOdbc;Version = 3;New=True;Compress=True;");

                // open the connection:
                conn.Open();

                // create a new SQL command:
                sqlite_cmd = conn.CreateCommand();

                // Let the SQLiteCommand object know our SQL-Query:
                sqlite_cmd.CommandText = "CREATE TABLE test2 (id integer primary key, text varchar(100));";

                // Now lets execute the SQL ;D
                sqlite_cmd.ExecuteNonQuery();

                // Lets insert something into our new table:
                sqlite_cmd.CommandText = "INSERT INTO test2 (id, text) VALUES (1, 'Test Text 1');";

                // And execute this again ;D
                sqlite_cmd.ExecuteNonQuery();
                label4.Text = "test2";
                label5.Text = "TestOdbc";
                // We are ready, now lets cleanup and close our connection:
                conn.Close();
            }

 //show inseted value from sqlite 



     private void button2_Click(object sender, EventArgs e)
            {
                try
                {
                    conn.ConnectionString = "Driver=SQLite3 ODBC Driver;Datasource=TestOdbc;Version = 3;New=True;Compress=True;";
                    conn.Open();
                    SQLiteCommand comm = new SQLiteCommand();
                    comm.Connection = conn;
                    comm.CommandText = "SELECT * FROM test2";
                    SQLiteDataReader created = comm.ExecuteReader();
                    MessageBox.Show("connection opened!!!");
                    while (created.Read()) // Read() returns true if there is still a result line to read
                    {
                    // Print out the content of the text field:
                    string myreader = "";
                    try
                    {
                        myreader = created[1].ToString();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    label3.Text="  "+myreader;
                }
                comm.Dispose();
                conn.Close();

            }
            catch (SQLiteException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

введите здесь описание изображения

person Avinash Shingole    schedule 14.09.2017