vb.net - How to add a record to an access database - visual basic
问题描述
I made a quiz which should store the users high score in a database however I keep getting an error satying 'Not allowed to change the 'ConnectionString'
Here is my code:
Imports System.Data.OleDb
Public Class Pure
Dim pro As String
Dim connstring As String
Dim command As String
Dim myconnection As OleDbConnection = New OleDbConnection
And here is the rest of the code which is supposed to add the highscore to the access database
Private Sub btnSummary_Click(sender As Object, e As EventArgs) Handles btnSummary.Click
pro = "provider=microsoft.ACE.OLEDB.12.0;Data Source=flashcard login.accdb" 'Establish connection with database
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open() 'Open connection
If lblScore11.Text > lblHighScore.Text Then 'If current socre is greater than high score
lblScore11.Text = lblHighScore.Text
command = " insert into results ([score]) values ('" & lblHighScore.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection) 'Establish connection
cmd.Parameters.Add(New OleDbParameter("score", CType(lblHighScore.Text, String)))
End If
End Sub
I added this try-catch statement at the end (Inside the if statement)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
解决方案
There are other issues, but the big one is you actually need to run the query:
cmd.ExecuteNonQuery()
Also, this query is still crazy-vulnerable to injection issues. This kind of string substitution is NEVER okay for an SQL string:
values ('" & lblHighScore.Text & "')"
Here's a full re-write with better patterns:
Dim connString As String = "provider=microsoft.ACE.OLEDB.12.0;Data Source=flashcard login.accdb"
Private Sub btnSummary_Click(sender As Object, e As EventArgs) Handles btnSummary.Click
If lblScore11.Text <= lblHighScore.Text Then Return
lblHighScore.Text = lblScore11.Text
Using conn As New OleDbConnection(connSstring), _
cmd As New OleDbCommand("INSERT INTO results ([score]) VALUES (?)", conn)
'Use the actual OleDbType that maps to the database column and length here
cmd.Parameters.Add("score", OleDbType.LongVarWChar).Value = lblScore11.Text
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
推荐阅读
- r - R:根据开始和结束日期扩展行并计算天之间的小时数
- node.js - 从 Sequelize 中的 dataValues 获取属性值
- python - Python 链表新节点
- javascript - 为什么我的基于 getComputedStyle 的语句没有运行?
- flutter - 如何在颤振中进行条件渲染
- c++ - QT/C++:使用主窗口调整自定义布局
- node.js - 错误:不能为不可为空的 postgress 返回 null
- python - 预定义函数的来源-numpy
- flutter - 设置 flutter_localizations 包时出错
- branch.io - Branch io:我应该如何配置链接,以便当用户单击尚未安装的Android应用程序的链接时打开默认应用程序市场?