How can I get my information to pass from my VB application to my Access Database table? - vb.net

So this is the code that I am using:
Public Class Form1
Dim dtmSystemDate As Date
Dim strResult As String
Dim Student As Double = Nothing
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBeginWorkout.Click
Dim cnn As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Dim Start As String = "Start"
' Set date/time to today's date/time.
dtmSystemDate = Now()
' Convert txtIDNumber to a Double.
Try
Student = CDbl(txtIDNumber.Text)
Catch ex As Exception
End Try
' Determine if input is a valid ID number.
If Student >= 10000 And Student <= 99999 Then
MessageBox.Show("Your start time is " & dtmSystemDate.ToString("F"), "Welcome, Student # " & Student.ToString())
Else
MessageBox.Show("Please enter a valid College ID number", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
)
End If
cnn.ConnectionString = "provider = microsoft.jet.oledb.4.0; data source = C:\users\econnelly\My Documents\Access Databases\Fit Track.mdb"
cnn.Open()
cmd.Connection = cnn
cmd.CommandText = "insert into Fit Track (Student_ID,Start/Stop,Date/Time) values ('" & Student & "','" & Start & "', '" & dtmSystemDate & "')"
cmd.ExecuteNonQuery()
cnn.Close()
I am attempting to pass these defined variables to an Access Database and so far have been unsuccessful.
Whenever I try to run my program, I get the following error:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
This error is triggering from the cmd.ExecuteNonQuery() function though I am not sure why.
As of yet, I have been unable to get the information to populate into the database at all. Can anyone point me in the right direction as to how to address this issue?

I believe the problem is with the table name "Fit Track" that has a space in it.
You could use square brackets like [Fit Track]
or you could use single quotes like 'Fit Track'

I don't know the answer, but I've ran into trouble when using spaces or special characters, like slashes, in database Table or Column names. Also, I think your connection string is incorrect. You might also want to read a little bit about SQL injection, it can be dangerous.
EDIT: You might also need to import System.Data.Oledb

Related

VB.NET database is not in MS Access and login error

I use Microsoft Access to store the data. The register form shows msgbox that the data was saved but there isn't any data stored in the table when I check the table on Microsoft Access. Is it supposed to be like that or did I code wrong?
This is my register code
If PasswordTextBox.Text.Length >= 8 Then
Try
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb")
Dim insert As String = "Insert into Table1 values('" & NameTextBox.Text & "','" & Staff_IDTextBox.Text & "','" & Phone_NoTextBox.Text & "','" & UsernameTextBox.Text & "','" & PasswordTextBox.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
'cmd.ExecuteNonQuery()
MsgBox("Saved")
For Each txt As Control In Me.Controls.OfType(Of TextBox)()
txt.Text = ""
Next
Catch ex As Exception
MsgBox("Error")
End Try
Else
MsgBox("Password must be more than 8 character")
End If
End If
This is my login code
uname = UsernameTextBox.Text
pword = PasswordTextBox.Text
Dim query As String = "Select password From Table1 where name= '" & uname & "';"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Try
pass = cmd.ExecuteScalar().ToString
Catch ex As Exception
MsgBox("Username does not exit")
End Try
If (pword = pass) Then
MsgBox("Login succeed")
Else
MsgBox("Login failed")
UsernameTextBox.Clear()
PasswordTextBox.Clear()
End If
There is an error at this line
pass = cmd.ExecuteScalar().ToString
It says:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Your "cmd.ExecuteNonQuery" is commented out, so the code will not save anything to the database.
You should close your connection after executing the INSERT command.
By default the table will have auto-numbered field as the first item in the table. You will need to remove this field from your table for that specific INSERT command to work.
Or you may need to use a slightly different INSERT command. It is useful to have auto-numbered ID fields in a table.
You probably should catch the exception and display ex.Message in your message box rather then "Error". The ex.Message will be much more helpful to you in debugging your program.
I have made all of these mistakes in my code at one time or other.
Your Login Code;
1)
You should catch the exception message and display in it a message box. This will make debugging faster.
The actual exception in your code will read "{"No value given for one or more required parameters."}
Your query is incorrect.
You should do the open, query, and close of the connection inside the Try-Catch block. Test for a null password afterwards to determine if the username does not exist.
Two separate answers provided, because you have two very separate questions.
Best wishes...

How to split a joined column into its seperate columns and use the data? (VB.Net + SQL Management Studio)

This is gonna be somewhat tricky to explain but I'll try to break it down. Note that this is created using VB.Net 2003.
I have a Web page which requires user to input data to save into SQL. They are required to fill in:
Course: {Select via drop-down table} \\ Variable name = Crse
Emp No: {Manually type the number} \\ Variable name = Emp
For the drop down list for Course, the data is obtained from an SQL table 'Course', with the columns:
| Course Code | Course Title |
Once input complete, I can then save the entry into my Emp_Course table in SQL using the query:
Dim updateState As String = "insert into EMP_COURSE" _
& "(Employee_No, CourseCode)" _
& "values('" & Emp.Text & "', " _
& "'"Crse.SelectedItem.ToString & "')"
Previously the drop-down list only needed the show Course Code, but now I'm required to add in the Course Title as well. Another thing to point out is that the Course Code has no fixed length.
Drop-down list sample:
Before:
A001
BX003
After:
A001 - Course A
BX003 - Course BX
Meaning I have to change the logic in populating the drop-down list:
Dim list As New SqlCommand("select CourseCode + ' - ' " _
& "+ CourseTitle as Course from [SQL].[dbo].[Course] " _
& "order by CourseCode", SQLDB)
Now comes my main issue, when I want to save my entry, the program obviously gives an error because the SQL still refers to the Course Code only, while my drop-down list is a Code + Description hybrid.
So since now I've made my course selection, how am I supposed to add to my SQL to update Emp_Course table to tell it to select the Course Code part of my hybrid selection?
I would just go to the Course table and just add a new Code + Title column and refer to that, but I have no authority to modify it and need to work around it.
Any other alternatives I can use?
Dim arr As String() = Crse.SelectedItem.ToString().Split(New Char() {"-"c})
Dim courseCode AS String = Trim(arr(0))
Dim updateState As String = "insert into EMP_COURSE" _
& "(Employee_No, CourseCode)" _
& "values('" & Emp.Text & "', " _
& "'"courseCode & "')"
Comments and explanations in line.
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Crse.DataSource = CreateDataSource()
'Course is the concatenated string returned from
'the database containing the CourseCode and the CourseTitle
Crse.DataTextField = "Course"
Crse.DataValueField = "CourseCode"
Crse.DataBind()
Crse.SelectedIndex = 0
End If
End Sub
Protected Function CreateDataSource() As DataTable
Dim dt As New DataTable
Using SQLDB As New SqlConnection("Your connection string")
'This selects the CourseCode as a separate column and the string called Course
'containing the CourseCode and the CourseTitle
Using cmd As New SqlCommand("select CourseCode, CourseCode + ' - ' + CourseTitle as Course from [SQL].[dbo].[Course] order by CourseCode", SQLDB)
SQLDB.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Return dt
End Function
Protected Sub UpdateDatabase()
Using SQLDB As New SqlConnection("Your connection string")
Using cmd As New SqlCommand("insert into EMP_COURSE (Employee_No, CourseCode) values(#EmpNo, #CourseCode);", SQLDB)
'I guessed at the SqlDbType. Check the database for the real data types.
cmd.Parameters.Add("EmpNo", SqlDbType.Int).Value = CInt(Emp.Text)
'Always use parameters to prevent SQL injection
'The SelectedValue will return the CourseCode
cmd.Parameters.Add("#CourseCode", SqlDbType.VarChar).Value = Crse.SelectedValue
SQLDB.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
UpdateDatabase()
End Sub
End Class
Split the value and get the course code as in the following code. Hope it helps.
Dim Str = Crse.SelectedItem.ToString
Dim strArr() As String
strArr = Str.Split(CType("-", Char()))
Dim CourseCode As String = strArr(0).Trim

Strange Update clause error (VB.NET)

I'm experiencing a really strange error. I have a table with only two columns (User and pass , both with text type).
The program asks first, what column I want to modify. With a radio button , I point which column I want to modify.
By pressing any radio button, two text boxes appear . You have to enter the password and the new data to modify it.
The problem is that when making the modification , if I want to change the user column , all is work well... But if I want to change a thing of the Password column , release "update error clause".
Honestly, I do not see any error in this code:
Protected Friend Sub modificarAcesso(ByVal column As String, ByVal dato As String)
Dim cmd As String = "Update Login SET " & column & "=#dato"
Try
con.Open()
comando = New OleDbCommand(cmd, con)
comando.Parameters.AddWithValue("#dato", dato)
comando.ExecuteNonQuery()
comando.Dispose()
con.Close()
Catch ex As Exception
con.Close()
MsgBox("Problemas en la consulta: " + ex.Message(), MsgBoxStyle.Critical)
End Try
End Sub
Password is a keyword, so you must put it in brackets. You should do this anyway if a column name has a space in it, too:
Dim cmd As String = "Update Login SET [" & column & "] = #dato"

datatypes dont match, correct query and table

Got a new one for you, tried everything i could think of but without succes.
I want to be able to edit some textboxes and then update their records in the database. I use this code:
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
connection.Open()
cmdupdate.CommandText = "UPDATE tbl_stal SET Locatie = '" & cbLocatienummer.Text & "', Coordinaten = '" & txtCoordinaten.Text & "' WHERE ID = '" & cbID.Text & "'"
cmdupdate.CommandType = CommandType.Text
cmdupdate.Connection = connection
cmdupdate.ExecuteNonQuery()
MsgBox("De gegevens zijn aangepast." & vbNewLine & "The data has been modified." & vbNewLine & "Die Daten sind angepasst.", MsgBoxStyle.OkOnly, "Voersoorten")
connection.Close()
cmdupdate.Dispose()
I am certain that the names of the database table and it's fields are correct, tried using both numerical and textbased settings on the table fields(as normally they should be numerical, but they might be text too. )
However, when i load some data from the datagridvieuw into the textboxes, change the coordinates(for example) and hit the updatebutton, it will give me the error that the datatypes don't match.
Apart from the above, what else can it be?
When you write data to a database table using any kind of sql text you should NEVER use string concatenation to build the SQL. This because you could have problems in the string supplied (what if one of these strings contains an embedded single quote?) and because taking the user input and attaching it to your command is a really dangerous practice that leads to Sql Injection
(Well MS-Access doesn't support multiple commands so you are a bit safer here)
So you should rewrite your query in this way
Dim cmdText = "UPDATE tbl_stal SET Locatie = ?, Coordinaten = ? WHERE ID = ?"
Using connection = new OleDbConnection(.....)
Using cmdUpdate = new OleDbCommand(cmdText, connection)
connection.Open()
cmdUpdate.Parameters.AddWithValue("#p1", cbLocatienummer.Text)
cmdUpdate.Parameters.AddWithValue("#p2", txtCoordinaten.Text)
cmdUpdate.Parameters.AddWithValue("#p3", Convert.ToInt32(cbID.Text))
cmdUpdate.ExecuteNonQuery()
End Using
End Using
Notice that you should provide a parameter with the exact datatype that matches the datatype of your field, strings for text fields, numbers for numeric fields.

no value given for one or more required parameters

What's wrong in here, I always get some nasty errors even if the same code that I used earlier works. But when I apply it to other form it gives me the error above.
here's my code:
Imports System.Data.OleDb
Public Class Updater2
Public adminID As String
Public adminName As String
Public adminPass As String
Private con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db1.mdb;Jet OLEDB:Database Password=nrew123$%^;")
Private com As OleDb.OleDbCommand
Public Sub New()
con.Open()
com = New OleDb.OleDbCommand("Select * from admintable")
com.Connection = con
End Sub
Public Sub updates()
com.CommandText = "UPDATE admintable SET AdminName = '" & adminName & "', AdminPassS = '" & adminPass & "' WHERE ID = '" & adminID & "'"
com.ExecuteNonQuery()
End Sub
End Class
And here's the code in the button which tries to update the data:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
shikai.adminID = textbox1.text
shikai.adminName = TextBox4.Text
shikai.adminPass = TextBox3.Text
shikai.updates()
MsgBox("Successfully updated!")
End Sub
what might be wrong here?
A good trick for dealing with a no value given for one or more required parameters error when developing for an Access back end is to grab the content of the CommandText and paste it into a dummy query in Access itself. Then Access will offer you a popup identifying which field is causing the problem (usually a typo, as in your case).
The usual reason for this error is a missing or misspelled value. It seems likely that adminName is Null or a zero-length string.
When pasting the command text into access itself and Access pops up telling you which field is the problem, if there does not appear to be a type, try enclosing the field name in square brackets. [ ] It is possible that one of your columns may contain a keyword. This happened to me, which the column LL_ID - I had to change it to [LL_ID].
SELECT pt.person_name,pt.obile_no,pt.address_info FROM person_table pt LEFT JOIN company_table ct ON pt.com_id=ct.com_id WHERE pt.com_id=14
I used it for access database then this type of erro "no value given for one or more required parameters" happened.
I actually did typo error like pt.obile, but it will be pt.mobile. When i corrected this was working well.
For my side, there is a field I have used in my query but not in my access db. After adding that field in ms access db, it works. May be you also need to check well if the field you have in query are the same as in your db