我将SQLite数据库名称存储在App.config中,并使用System.Configuration参考来检索数据库名称
我认为这没有任何价值,因此删除了readConfig代码
现在我无法创建数据库及其两个表
有人会友好地检查下面的代码并解释我做错了吗?
在模块中设置
Public gv_dbName As String = "Notes.db"
frmStart的顶层声明
Public connStr As String = "Data Source={0};Version=3;"
Public conn As SqliteConnection
Dim cmd As SqliteCommand
其他相关代码
Private Sub frmStart_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath)
connStr = String.Format(connStr, gv_dbName)
If My.Computer.FileSystem.FileExists(gv_dbName) Then
btnCreate.Visible = False
btnToEnterData.Visible = True
btnToViewParentTable.Visible = True
ElseIf Not My.Computer.FileSystem.FileExists(gv_dbName) Then
conn = New SqliteConnection($"Data Source = '{gv_dbName}';Version=3;")
tbMessage.Text = "Created Database & Tables"
End If
End Sub
Private Sub btnCreate_Click(sender As Object, e As EventArgs) Handles btnCreate.Click
makeDB()
End Sub
Public Sub makeDB()
If Not My.Computer.FileSystem.FileExists(gv_dbName) Then
Try
conn = New SqliteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
makeParentTable()
makeChildTable()
conn.Close()
Catch ex As Exception
tbMessage.Text = "Database NOT Created"
End Try
End If
End Sub
我什至尝试了frmStart的最高级别
'Friend gv_dbName As String = "Notes.db"
这是我基于此代码编写的内容
Link to Code
答案 0 :(得分:1)
假设Notes.db位于应用程序目录(exe所在的目录)中,这就是在sqlite上打开连接的方式。只需删除不需要的选项即可。
New=True
如果Open()失败,则可以尝试在连接字符串中添加conn = New SQLiteConnection(strConString & "New=True;")
newArr.push({})
答案 1 :(得分:1)
使用Microsoft.Data.Sqlite.Core
或System.Data.SQLite
(Db版本3) 可以确定文件是否存在。
只需给出一个 物理/绝对 路径,如果不存在,则创建一个新文件named.db
,否则,现有数据库返回:
示例:
Friend dbPath As String = IO.Path.Combine(Application.StartupPath, "Notes.db")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TestMySqlite()
End Sub
Private Sub TestMySqlite()
Try
'You can use this but it is not important for version 3 as is auto created the new file by itself
'If Not IO.File.Exists(dbPath) Then SQLiteConnection.CreateFile(dbPath)
Using conn As SQLiteConnection = New SQLiteConnection("Data Source=" & dbPath & "; Version=3;")
conn.Open()
Console.WriteLine(conn.FileName)
Using command As SQLiteCommand = New SQLiteCommand("CREATE TABLE IF NOT EXISTS Test (RowIndex INTEGER PRIMARY KEY AUTOINCREMENT COLLATE NOCASE, name varchar(20))", conn)
command.ExecuteNonQuery()
End Using
Using cmdInsert = New SQLiteCommand("INSERT INTO Test (name) values ('this is a test')", conn)
cmdInsert.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Console.WriteLine(ex.ToString)
Stop
End Try
End Sub
在此示例中,将在您的应用程序正在运行的文件夹下创建一个名为Notes.db的文件(如果不存在)。 下次调用SQLiteConnection只是返回Notes.db