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)
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)
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.
When I try to connect to AcessDB, I get the error
"Keyword is not supported: provider".
When I try to change provider, I get another error. When I delete provider tag, I also get an error.
Dim Exists As Boolean = False
Dim ConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Name\Documents\Visual Studio 2010\Projects\datagrid\datagrid\pokus.accdb;Persist Security Info=False;"
Dim connection As New SqlConnection(ConnectionString)
Try
connection.Open()
Dim command As SqlCommand = connection.CreateCommand
command.CommandText = "SELECT * FROM studenti"
Dim reader As SqlDataReader = command.ExecuteReader
If reader.HasRows Then
Exists = True
Else
Exists = False
End If
reader.Close()
command.Dispose()
Catch ex As Exception
Console.Write(ex.Message)
Finally
connection.Close()
End Try
SqlConnection, SqlCommand, etc. are SQL Server-specific classes. You can't use them to connect to MS Access.
The documentation for SqlConnection makes this very clear:
Represents an open connection to a SQL Server database.
Consider using the OldDbConnection and related classes instead.
I always write wrapper classes for database connections, and I always recommend the same.
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Name\Documents\Visual Studio 2010\Projects\datagrid\datagrid\pokus.accdb;Persist Security Info=False;"
Dim Conn As New OleDbConnection
Conn.ConnectionString = sConnectionString
Conn.Open()
Dim sQuery As String = "SELECT * FROM studenti"
Dim da As New OleDbDataAdapter(sQuery, Conn)
Dim dt As New DataTable
da.Fill(dt)
Conn.Close()
This is my code I have put behind my submit button, I have two text boxes Name and E-mail that I want to be added to my database that it does not work wonder if anyone can help
Dim Strnm As String = Request.Form("txtname")
Dim Strem As String = Request.Form("txtemail")
Dim objConnection As OleDbConnection = Nothing
Dim objcmd As OleDbCommand = Nothing
Dim StrSQL As String
Dim dbConn As OleDbConnection = Nothing
Dim filepath = "G:\WebSites\WebSite1\App_Data\register_log.ldf"
dbConn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\registration.accdb")
dbConn.Open()
StrSQL = "insert into tblregistration (Name, E-mail) values (?,?)"
objcmd = New OleDbCommand(StrSQL, dbConn)
objcmd.Parameters.Add(New System.Data.OleDb.OleDbParameter("#txtname", Strnm))
objcmd.Parameters.Add(New System.Data.OleDb.OleDbParameter("#txtemail", Strem))
'close connection
dbConn.Close()
Response.Write("submitted successfully")
You did not execute the query. Your code can be also be shortened with Using blocks which declare and dispose of things:
Dim Strnm As String = Request.Form("txtname")
Dim Strem As String = Request.Form("txtemail")
Dim StrSQL = "insert into tblregistration (Name, E-mail) values (?,?)"
Using dbConn = New OleDbConnection(connection string...),
objcmd = New OleDbCommand(StrSql, objConnection)
dbConn.Open()
objcmd.Parameters.Add(New System.Data.OleDb.OleDbParameter("#txtname", Strnm))
objcmd.Parameters.Add(New System.Data.OleDb.OleDbParameter("#txtemail", Strem))
objcmd.ExecuteNonQuery ' execute the query
End Using ' close and dispose of dbConn, objcmd
Response.Write("submitted successfully")
There are also 2 Connection objects declared (objConnection and dbConn) in the code.
Using acts like Dim in so far the code can declare and initialize things in one line of code. But mainly it assures that these things are closed and disposed of at the end of the block. The code also uses the constructor to pass the SQL and Connection to dbConn and objCmd when they are created. It only saves a line or two of code, but assumes that they have what they need from the moment they are created.
You can write also use a function to return a Connection object so that you do not have to have the connection string throughout your code. See this answer.
I have a VB.Net app that should enable the user to import CSV file into the datagrid (which it does) and then update those rows to a table in Oracle.
Here is what I have so far but it doesn't seem to work neither throw an error.
Private Sub Update_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Update.Click
MsgBox("Saving...")
Dim table As New DataTable()
Dim BindingSource As New BindingSource()
BindingSource.DataSource = table
table.Columns.Add("ORDER_NO")
table.Columns.Add("LINE_ITEM_NO")
table.Columns.Add("CONTRACT")
table.Columns.Add("PART_NO")
table.Columns.Add("QTY_REQUIRED")
table.Columns.Add("QTY_PER_ASSEMBLY")
table.Columns.Add("RELEASE_NO")
table.Columns.Add("SEQUENCE_NO")
table.Columns.Add("ORDER_CODE")
table.Columns.Add("PART_OWNERSHIP")
Dim parser As New FileIO.TextFieldParser("C:\Documents and Settings\User\Desktop\solution.csv")
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True
parser.TrimWhiteSpace = True
parser.ReadLine()
Dim sConnectionString As String = "Data
Source=MYSERVER.COM;User ID=MYNAME;Password=MYPASSWD;"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOC_TAB(ORDER_NO,
LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY,
RELEASE_NO,SEQUENCE_NO,ORDER_CODE,PART_OWNERSHIP) VALUES (#ORDER_NO,
#LINE_ITEM_NO,#CONTRACT,#PART_NO,#QTY_REQUIRED,#QTY_PER_ASSEMBLY,#RELEASE_NO,#SEQUENCE_NO,#ORDER_CODE,#PART_OWNERSHIP)"
Using conn As New OracleClient.OracleConnection(sConnectionString)
Dim adapter As New OracleDataAdapter
Dim cmd As New OracleClient.OracleCommand()
cmd.Connection = conn
cmd.Connection.Open()
cmd.CommandText = strSql
adapter.InsertCommand = New OracleCommand(strSql, conn)
adapter.UpdateCommand = cmd
adapter.Update(table)
'--cmd.ExecuteReader()
cmd.Connection.Close()
MsgBox("Saved! Kindly check your Shop order!")
DataGridView1.DataSource = Nothing
End Using
End Sub
Now I have brought it down to inserting records in the table, but problem is it only parses the first column in the row.
So all suppose 6 columns in the table are updated with values from the first field in the CSV.
MsgBox("Saving...")
Dim parser As New FileIO.TextFieldParser("C:\Documents and Settings\nUser\Desktop\solution.csv")
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True
parser.TrimWhiteSpace = True
Dim i As Integer
For i = 0 To DataGridView1.RowCount - 1
Dim CurrentField = parser.ReadFields()
'--parser.ReadLine()
Dim sConnectionString As String = "Data Source=MYSERVER.COM;User ID=MYUSER;Password=MYPASSWD;"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOCT(ORDER_NO, LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY) VALUES (:ORDER_NO, :LINE_ITEM_NO,:CONTRACT,:PART_NO,:QTY_REQUIRED,:QTY_PER_ASSEMBLY)"
Using conn As New OracleClient.OracleConnection(sConnectionString)
Using cmd As New OracleClient.OracleCommand()
Dim adapter As New OracleDataAdapter
conn.Open()
cmd.Connection = conn
cmd.CommandText = strSql
cmd.Parameters.AddWithValue("ORDER_NO", CurrentField(i))
cmd.Parameters.AddWithValue("LINE_ITEM_NO", CurrentField(i))
cmd.Parameters.AddWithValue("CONTRACT", CurrentField(i))
cmd.Parameters.AddWithValue("PART_NO", CurrentField(i))
cmd.Parameters.AddWithValue("QTY_REQUIRED", CurrentField(i))
cmd.Parameters.AddWithValue("QTY_PER_ASSEMBLY", CurrentField(i))
cmd.CommandText = strSql
adapter.InsertCommand = New OracleCommand(strSql, conn)
adapter.UpdateCommand = cmd
'adapter.Update(table)
cmd.ExecuteNonQuery()
cmd.Connection.Close()
DataGridView1.DataSource = Nothing
End Using
End Using
Next
Never used oracle so please ignore me if I'm being stupid.
Have you tried conn.Connect() rather than cmd.Connection.Open()?
I don't understand the part of your code that create a DataTable and add columns.
It's not used anywhere, so is not related to your issue.
Let's look at code relating data connection
' If I remember well, the parameters in an oracle statement are prefixed by a ":"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOC_TAB(ORDER_NO," +
"LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY, " +
"RELEASE_NO,SEQUENCE_NO,ORDER_CODE,PART_OWNERSHIP) VALUES (:ORDER_NO, " +
":LINE_ITEM_NO,:CONTRACT,:PART_NO,:QTY_REQUIRED,:QTY_PER_ASSEMBLY, " +
":RELEASE_NO,:SEQUENCE_NO,:ORDER_CODE,:PART_OWNERSHIP)"
' Connection and Command are Disposable, so use `Using` around them
Using conn As New OracleClient.OracleConnection(sConnectionString)
Using cmd As New OracleClient.OracleCommand()
Dim adapter As New OracleDataAdapter
conn.Open()
cmd.Connection = conn
cmd.CommandText = strSql
' Now you need to add the parameters to your command
' One parameter for each column used in the insert statement
' I suppose that values for the paramenter are in the current line from your CSV
cmd.Parameters.Add("ORDER_NO", OracleType.VarChar).Value = parser[index_of_orderNumber_Text])
' .... other parameters to be added....
' Now you can execute the INSERT statement directly with your command
cmd.ExecuteNonQuery()
End Using
And, as last thing, the OracleClient namespace has been deprecated by Microsoft, so you should try to replace with ODP directly from Oracle.