I am trying to add a new record to an Access database. I am new to Visual Basic but have been searching for an answer to this. Here is my code so far:
Dim ID As Integer = CInt(IDBox.Text)
Dim password As Integer = CInt(PasswordBox.Text)
Dim first As String = FirstName.Text
Dim last As String = LastName.Text
Dim access As Integer = CInt(AccessLevel.Text)
Dim conn As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Tristan\Documents\Visual Studio 2015\Projects\Keno\Keno\Users.accdb")
conn.Open()
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
da = New OleDb.OleDbDataAdapter("SELECT * FROM Users", conn)
da.Fill(ds, "Users")
Dim cb As New OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("Users").NewRow()
dsNewRow.Item("ID") = ID
dsNewRow.Item("First_Name") = first
dsNewRow.Item("Last_Name") = last
dsNewRow.Item("Password") = password
dsNewRow.Item("Access_Level") = access
ds.Tables("Users").Rows.Add(dsNewRow)
cb.GetInsertCommand()
da.Update(ds, "Users")
conn.Close()
MsgBox("User added successfully!")
Running this gets an error:
An unhandled exception of type System.Data.OleDb.OleDbException
occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
Any help is appreciated!
The issue is almost certainly the fact that "Password", which you have used as a column name, is a reserved word. Any identifiers used in SQL code that are reserved words or contain special characters, e.g. spaces, must be escaped. A command builder doesn't do that by default. You have to set the QuotePrefix and QuoteSuffix properties yourself to make it do so. For an Access database, you would use "[" and "]" as the property values respectively.
Related
I am trying to connect to an ODBC connection.
This works.
Dim cn As OdbcConnection
cn = New OdbcConnection("DRIVER={SQL Server};SERVER=ServerName;UID=UserName;" &
"PWD=Password;DATABASE=dbName;")
Dim mystring As String = "SELECT * FROM dbo_lData WHERE S_DT > #3/18/2018#"
Dim cmd As OdbcCommand = New OdbcCommand(mystring)
cn.Open()
MsgBox("Connected")
cn.Close()
I've tried a couple of variations using different code that I've found on the internet, but I keep getting the same error. Error 42000, incorrect syntax near #. Here is the code.
Dim selectSQL As String = "SELECT * FROM dbo_lData WHERE S_DT > #3/18/2018#"
cn = New OdbcConnection("DRIVER={SQL Server};SERVER=ServerName;UID=UserName;" &
"PWD=Password;DATABASE=dbName;")
Dim custDA As New OdbcDataAdapter
Dim selectCMD As OdbcCommand = New OdbcCommand(selectSQL, cn)
custDA.SelectCommand = selectCMD
Dim custDS As DataSet = New DataSet
custDA.Fill(custDS, "lData")
DataGridView1.Visible = True
DataGridView1.DataSource = custDA
I'm pretty lost on this, but what I am trying to do is just...
Make ODBC Connection
Load results, preferable into a datatable
Set datagridview.datasource = datatable
The error you are getting is referring to your Select statement. As the comments said use parameters. First double check the data type of S_DT column. I wonder why you are using ODBC when the SQL server native provider SQLClient will yield better results.
Dim cn As New OdbcConnection("connection string")
Dim cmd As New OdbcCommand("SELECT * FROM dbo_lData WHERE S_DT > #sdate", cn)
cmd.Parameters.Add("#sdate", OdbcType.Date)
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I am trying to create a ticket system, this part of the system will display all of the acts performing on each specific day. I am also trying to show how many tickets/seats are available. I have a database with all seat locations and a boolean value to show if they are taken or not.
Public ds As New DataSet 'used to store the basic elements of the database
Public con As New OleDb.OleDbConnection 'used to connect to the database
Public provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Public datafile As String = "Resources/database.accdb" 'database location and version
Public da As OleDb.OleDbDataAdapter
Public sqlstatement As String
Public connString As String = provider & datafile
lbxActs.Items.Clear()
Dim oDataRowView As DataRowView
Dim sSelectedAssetType As String
ds.Clear()
con.ConnectionString = connString
con.Open()
sqlstatement = "SELECT ShowDate FROM AvailableDates"
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "Dates")
lbxDates.DataSource = ds.Tables("Dates")
lbxDates.DisplayMember = "ShowDate"
lbxDates.ValueMember = "ShowDate"
con.Close()
oDataRowView = CType(Me.lbxDates.SelectedItem, DataRowView)
sSelectedAssetType = oDataRowView("ShowDate").ToString
lbxActs.Items.AddRange(IO.File.ReadAllLines("Resources/" & sSelectedAssetType & ".txt"))
con.Close()
ds.Clear()
con.ConnectionString = connString
con.Open() 'Open connection to the database
sqlstatement = "SELECT * FROM [Seats" & sSelectedAssetType & "] WHERE [Available] = True "
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "seats") 'Fill the data adapter
con.Close()
Dim recordCount, x As Short
recordCount = 0
x = 0
recordCount = ds.Tables("seats").Rows.Count
tbxLeftS.Text = recordCount
the first part of the program puts all the show dates into a list box, then depending on which one is clicked it shows a different list of acts from my text files. The second part of the program is supposed to use an SQL statement to find all the seat locations which are available. Then it counts the records and then displays the number in a text box.
Object reference not set to an instance of an object
This error appears 4 times and it highlights this line:
sSelectedAssetType = oDataRowView("ShowDate").ToString
To get rid of the error, its very likely that somehow oDataRowView is null. You need to check to make sure its not null before you try to convert it to a string. Do something like this:
IF Not isdbnull(oDataRowView)
oDataRowView = CType(Me.lbxDates.SelectedItem, DataRowView)
End if
As to why you are getting a null value for oDataRowView, that will require you to debug further. Perhaps it could be an issue with PostBack (assuming this is a web page and not winforms.
Having some issues with the myDataAdapter.fill line, getting the error "syntax error in From clause" looked around at other solutions and none have worked, most seem to be about reserved words - all out of ideas, help!
'retrieve the connection string from the ConnectionString Key in Web.Config
'string connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Woof.mdb"
Dim myDataSet As New System.Data.DataSet("Email")
'create a new OleDB connection
Dim conn As New System.Data.OleDb.OleDbConnection(connectionString)
'pass the Select statement and connection information to the initializxation constructor for the OleDBDataAdapter
Dim myDataAdapter As New System.Data.OleDb.OleDbDataAdapter("SELECT Email FROM Email-list", conn)
'Fill the dataset and table with the data retrieved by the select command
myDataAdapter.Fill(myDataSet, "Email")
Dim str As String = myDataSet.ToString
Label3.Text = str
Use the query
Dim myDataAdapter As New System.Data.OleDb.OleDbDataAdapter("SELECT Email FROM [Email-list]", conn)
The problem I am having is as follows:
I am using an SQL query to take data out of a table like so:
Dim query As String = "SELECT Pronunciation, Character FROM [Hiragana List] WHERE Pronunciation='" & pronunciation & "';"
Dim instruction = New SqlCommand(query, sqlCon)
Dim da As New SqlDataAdapter
da.SelectCommand = instruction
da.Fill(HiraganaList)
This should then take the data from the table and fill-in a datatable called "Hiragana List", however when the code reaches the line
da.Fill(Hiragana List)
The operation of the program stops and it instead returns this error:
An unhandled exception of type 'System.ArgumentNullException' occurred in System.Data.dll
Additional information: Value cannot be null.
I took a look at the "Hiragana List" table itself and changed it so that it would accept Nulls in each of the field in order to see if it would fix it, unfortunately it still returns the same error.
(edit) Here is the declaration for the datatable 'Hiragana List':
Dim connectionString As String = "Server=my_server;Database=name_of_db;User Id=user_name;Password=my_password"
Dim sqlCon = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename='J:\Computing Coursework\real project\KES\KES\Kana List.mdf';Integrated Security=True;Connect Timeout=30")
Dim HiraganaList As DataTable
Dim KanjiList As DataTable
Dim Katakana As DataTable
Dim YoonList As DataTable
Dim YoonKataList As DataTable
Ok on your code befor da.Fill(HiraganaList) add this Code :
HiraganaList = New DataTable
you Need this to avoid null Exception.
I am puzzled by why it does not retrieve the data and keep saying i have a error "InvalidCastException", i am currently doing these in compact framework and is totally new to it, i searched around looking for a way to get data into a listview base on what little i know about java .
these are my creation of table and inserting during formload
Dim createTable3 As SqlCeCommand = connection.CreateCommand
createTable3.CommandText = "CREATE TABLE product(product_id int IDENTITY(0,1) PRIMARY KEY,product_name nvarchar(50),bought_price float,sales_price float)"
connection.Open()
createTable3.ExecuteNonQuery()
Dim insertCmd2 As SqlCeCommand = connection.CreateCommand
insertCmd2.CommandText = "INSERT INTO product(product_name,bought_price)Values('Food',1.00)"
insertCmd2.ExecuteNonQuery()
Dim insertCmd3 As SqlCeCommand = connection.CreateCommand
insertCmd3.CommandText = "INSERT INTO product(product_name,bought_price)Values('Orange',1.50)"
insertCmd3.ExecuteNonQuery()
Dim insertCmd4 As SqlCeCommand = connection.CreateCommand
insertCmd4.CommandText = "INSERT INTO product(product_name,bought_price)Values('Apple',3.00)"
insertCmd4.ExecuteNonQuery()
Dim insertCmd5 As SqlCeCommand = connection.CreateCommand
insertCmd5.CommandText = "INSERT INTO product(product_name,bought_price)Values('Fruit',2.00)"
insertCmd5.ExecuteNonQuery()
connection.Close()
this is a code for a get info button
Dim itmListItem As ListViewItem
Dim shtFieldCntr As Short
Dim loopCmd As SqlCeCommand = connection.CreateCommand
loopCmd.CommandText = "SELECT * FROM product"
connection.Open()
Dim dr As SqlCeDataReader = loopCmd.ExecuteReader
Do While dr.Read
itmListItem = New ListViewItem()
If dr.IsDBNull(dr(0)) Then
itmListItem.Text = ""
Else
itmListItem.Text = dr(0)
End If
For shtFieldCntr = 1 To dr.FieldCount()
If dr.IsDBNull(shtFieldCntr) Then
itmListItem.SubItems.Add("")
Else
itmListItem.SubItems.Add(dr.GetString(shtFieldCntr)) ' error this line
End If
Next shtFieldCntr
lvProduct.Items.Add(itmListItem)
Loop
connection.Close()
picture
If you review the documentation for SqlCeDataReader.GetString, it mentions under "Remarks" that:
No conversions are performed;
therefore, the data retrieved must
already be a string.
This will be why you're getting an InvalidCastException. None of your fields, except for product_name, are strings. What you need to do is something like:
itmListItem.SubItems.Add(Convert.ToString(dr.GetValue(shtFieldCntr)))
When you know what all the fields in a table are, it would make more sense to call them and then add them to SubItems explicitly i.e:
Dim productId As Int32 = dr.GetInt32(dr.GetOrdinal("product_id"))
Dim productName As String = dr.GetString(dr.GetOrdinal("product_name"))
itmListItems.SubItems.Add(productId)
itmListItems.SubItems.Add(productName)