SpongeBob SquarePants
SpongeBob SquarePants

Reputation: 1055

Unable to create a table & insert values in the database

The below code is suppose to create a database and a table with a column "FirstName" which is assigned a value "James"

Imports System.Data.SQLite
Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SQLiteConnection.CreateFile("c:\mydatabasefile.db3")
        Dim sqlConnection As New SQLite.SQLiteConnection()
        Dim sqlCommand As New SQLiteCommand

        sqlConnection.ConnectionString = "Data Source=c:\mydatabasefile.db3"
        sqlConnection.Open()
        sqlCommand.CommandText = "CREATE TABLE MyTable(EmpID INTEGER PRIMARY KEY ASC,  FirstName VARCHAR(25));"
        sqlCommand.CommandText = "INSERT INTO MyTable(FirstName) VALUES('James');"
        sqlConnection.Close()
    End Sub
End Class

But for some reason the app only creates a a database which has a size of 0 bytes. Why is it not working . I am using I am using SQLite ADO.NET Provider. , VS 2010, Winforms

Upvotes: 1

Views: 1992

Answers (3)

msarchet
msarchet

Reputation: 15232

You are never executing the sql commands

Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SQLiteConnection.CreateFile("c:\mydatabasefile.db3")
        Dim sqlConnection As New SQLite.SQLiteConnection()
        Dim sqlCommand As New SQLiteCommand("", sqlConnection)

        sqlConnection.ConnectionString = "Data Source=c:\mydatabasefile.db3"
        sqlConnection.Open()
        sqlCommand.CommandText = "CREATE TABLE MyTable(EmpID INTEGER PRIMARY KEY ASC,  FirstName VARCHAR(25));"
        sqlCommand.ExecuteNonQuery()
        sqlCommand.CommandText = "INSERT INTO MyTable(FirstName) VALUES('James');"
        sqlCommand.ExecuteNonQuery()
        sqlConnection.Close()
    End Sub


End Class

You also need to be setting the Commands Connection which you can also do by saying

sqlCommand.Connection = sqlConnection That should fix you up

Upvotes: 2

Tim
Tim

Reputation: 5421

Also let the command know what connection to use. sqlCommand.Connection = sqlConnection

Upvotes: 1

Anders Zommarin
Anders Zommarin

Reputation: 7274

You never execute the sqlCommands. You should use .ExecuteNonQuery() to get something into the database, otherwise nothing will be done.

Upvotes: 1

Related Questions