vb.net - 未创建 SQLite 数据库创建
问题描述
我将我的 SQLite 数据库名称存储在 App.config 中并使用 System.Configuration Reference 来检索数据库名称
我认为这没有任何价值,所以我删除了 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"
这是我基于
链接到代码的代码
解决方案
使用Microsoft.Data.Sqlite.Core
or System.Data.SQLite
(Db Version 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
推荐阅读
- java - 如何判断哪个玩家获胜
- java - 如何为 API 测试创建 JSESSIONID
- ruby-on-rails - Rails - Puma 随机无法启动工人
- sql - Postgresql:适用于(时间戳,字符串)的多列索引
- tensorflow - 下载预编译的二进制文件 libtensorflow.so 和 libtensorflow_framework.so
- hyperledger-fabric - 作曲家网络开始:没有来自任何对等方的有效响应。来自尝试的对等通信的响应是一个错误:错误:REQUEST_TIMEOUT
- qt - 更改 SplitView 大小不尊重 ColumnLayout minimumWidth?
- arrays - 数组的编译器支持 | 形式参数
- testing - 在 Grails 3.3.1 单元测试中记录 SQL
- python - 来自 __init__.py 的 ReadTheDocs 导入错误