Getting Syntax Error Converting from Datetime Character String - sql-server

I have the following code:
Imports System.Data.SqlClient
Public Class Main
Protected WithEvents DataGridView1 As DataGridView
Dim instForm2 As New Exceptions
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles startpayrollButton.Click
Dim ssql As String = "select MAX(payrolldate) AS [payrolldate], " & _
"dateadd(s, 518399, max(payrolldate)) AS [Sunday]" & _
"from dbo.payroll" & _
" where payrollran = 'no'"
Dim oCmd As System.Data.SqlClient.SqlCommand
Dim oDr As System.Data.SqlClient.SqlDataReader
oCmd = New System.Data.SqlClient.SqlCommand
Try
With oCmd
.Connection = New System.Data.SqlClient.SqlConnection("Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx")
.Connection.Open()
.CommandType = CommandType.Text
.CommandText = ssql
oDr = .ExecuteReader()
End With
If oDr.Read Then
payperiodstartdate = oDr.GetDateTime(1)
payperiodenddate = payperiodstartdate.AddDays(7)
Dim ButtonDialogResult As DialogResult
ButtonDialogResult = MessageBox.Show(" The Next Payroll Start Date is: " & payperiodstartdate.ToString() & System.Environment.NewLine & " Through End Date: " & payperiodenddate.ToString())
If ButtonDialogResult = Windows.Forms.DialogResult.OK Then
exceptionsButton.Enabled = True
startpayrollButton.Enabled = False
End If
End If
oDr.Close()
oCmd.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
oCmd.Connection.Close()
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click
Dim connection As System.Data.SqlClient.SqlConnection
Dim adapter As System.Data.SqlClient.SqlDataAdapter = New System.Data.SqlClient.SqlDataAdapter
Dim connectionString As String = "Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx"
Dim ds As New DataSet
Dim _sql As String = "SELECT [Exceptions].Employeenumber,[Exceptions].exceptiondate, [Exceptions].starttime, [exceptions].endtime, [Exceptions].code, datediff(minute, starttime, endtime) as duration into Scratchpad3" & _
" FROM Employees INNER JOIN Exceptions ON [Exceptions].EmployeeNumber = [Exceptions].Employeenumber" & _
" where [Exceptions].exceptiondate between #payperiodstartdate and #payperiodenddate" & _
" GROUP BY [Exceptions].Employeenumber, [Exceptions].Exceptiondate, [Exceptions].starttime, [exceptions].endtime," & _
" [Exceptions].code, [Exceptions].exceptiondate"
connection = New SqlConnection(connectionString)
connection.Open()
Dim _CMD As SqlCommand = New SqlCommand(_sql, connection)
_CMD.Parameters.AddWithValue("#payperiodstartdate", payperiodstartdate)
_CMD.Parameters.AddWithValue("#payperiodenddate", payperiodenddate)
adapter.SelectCommand = _CMD
Try
adapter.Fill(ds)
If ds Is Nothing OrElse ds.Tables.Count = 0 OrElse ds.Tables(0).Rows.Count = 0 Then
'it's empty
MessageBox.Show("There was no data for this time period. Press Ok to continue", "No Data")
connection.Close()
Exceptions.saveButton.Enabled = False
Exceptions.Hide()
Else
connection.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
connection.Close()
End Try
Exceptions.Show()
End Sub
Private Sub payrollButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles payrollButton.Click
Payrollfinal.Show()
End Sub
End Class
and when I run this code, I get the following error
System.Data.SQLClient.SQLException:
Syntax error converting from datetime
character string, line 57.
Which is this line:
adapter.Fill(ds)
When I debug this, I put the line break on that line and look at the Table Value, which shows 0, but I know that there is data for that time frame. Can anyone please assist?

Check this out -- you may have a problem with nullable datetimes:
Linky

Related

Unable to convert System.Date and System.int to System.String, error

I'm trying to search a keyword in the SQL Server db from Textbox1 and printing the corresponding details in other TextBoxes.
While running the below code, it shows it is unable to convert the DateTime and Integer value into String to display it in the TextBoxes.
Also there is another end of statement expected error in the command.Parameter line:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connection As New SqlConnection("Server= DESKTOP-STMQUHM; Database = HospitalDB;Trusted_Connection=True")
Dim command As New SqlCommand("select * from Medicines where MedicineName ='" & TextBox1.Text & "' ", connection)
command.Parameters.Add("#Textbox1",SqlDbType.Text)Value=TextBox1.Text 'Another error
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
If table.Rows.Count() > 0 Then
TextBox1.Text = table.Rows(0)(1).ToString
TextBox2.Text = table.Rows(0)(2).ToString
TextBox3.Text = table.Rows(0)(3).ToString
TextBox4.Text = table.Rows(0)(4).ToString
Else
MessageBox.Show("NO DATA FOUND!!")
End If
End Sub
Try to change this:
Dim command As New SqlCommand("select * from Medicines where MedicineName ='" & TextBox1.Text & "' ", connection)
command.Parameters.Add("#Textbox1",SqlDbType.Text)Value=TextBox1.Text
Into this:
Dim command As New SqlCommand("select * from Medicines where MedicineName = #MedicineName", connection)
command.Parameters.Add("#MedicineName",SqlDbType.Text).Value=TextBox1.Text
This is because you have not declared the parameter name into your original SQL string, then on the second line of your code, before Value, you're missing a dot.

How to import text file in vb.net and insert into SQL server?

I'm trying to import a text file into an SQL server. I need to read data inside the file when I upload it and send all the data to an SQL server. Of course inside the SQL I have primary keys where it's going to increment when a new line of data is finished.
HELP!
With Cinchoo ETL - an open source ETL framework, you can load the entire file to database with few lines of code as below (the code is in c#, hope you can translate it to vb.net)
string connectionstring =
#"Data Source=(localdb)\v11.0;Initial Catalog=TestDb;Integrated Security=True";
using (SqlBulkCopy bcp = new SqlBulkCopy(connectionstring))
{
using (var dr = new ChoCSVReader<Customer>
("Cust.csv").WithFirstLineHeader().AsDataReader())
{
bcp.DestinationTableName = "dbo.Customers";
bcp.EnableStreaming = true;
bcp.BatchSize = 10000;
bcp.BulkCopyTimeout = 0;
bcp.NotifyAfter = 10;
bcp.SqlRowsCopied += delegate (object sender, SqlRowsCopiedEventArgs e)
{
Console.WriteLine(e.RowsCopied.ToString("#,##0") + " rows copied.");
};
bcp.WriteToServer(dr);
}
}
For more details, visit the codeproject article
Disclosure: I'm the author of this library.
This is an interesting question. I did this a looonnngggg time ago. See the code below, for a solution to your question.
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim tblReadCSV As New DataTable()
tblReadCSV.Columns.Add("FName")
tblReadCSV.Columns.Add("LName")
tblReadCSV.Columns.Add("Department")
Dim csvParser As New TextFieldParser("C:\Users\Excel\Desktop\Employee.txt")
csvParser.Delimiters = New String() {","}
csvParser.TrimWhiteSpace = True
csvParser.ReadLine()
While Not (csvParser.EndOfData = True)
tblReadCSV.Rows.Add(csvParser.ReadFields())
End While
Dim con As New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
Dim strSql As String = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)"
'Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Connection = con
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName")
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName")
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department")
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
Dim result As Integer = dAdapter.Update(tblReadCSV)
End Sub
Also, see ALL the code below, for several similar, and related, tasks. Notice, I added a few comments, but not too many...
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.OleDb
Imports System.Configuration
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim headers = (From header As DataGridViewColumn In DataGridView1.Columns.Cast(Of DataGridViewColumn)() Select header.HeaderText).ToArray
Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not row.IsNewRow Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
Dim str As String = ""
Using sw As New IO.StreamWriter("C:\Users\Excel\Desktop\OrdersTest.csv")
sw.WriteLine(String.Join(",", headers))
'sw.WriteLine(String.Join(","))
For Each r In rows
sw.WriteLine(String.Join(",", r))
Next
sw.Close()
End Using
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'Dim m_strConnection As String = "server=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;"
'Catch ex As Exception
' MessageBox.Show(ex.ToString())
'End Try
'Dim objDataset1 As DataSet()
'Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Dim da As OdbcDataAdapter
Dim OpenFile As New System.Windows.Forms.OpenFileDialog ' Does something w/ the OpenFileDialog
Dim strFullPath As String, strFileName As String
Dim tbFile As New TextBox
' Sets some OpenFileDialog box options
OpenFile.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*" ' Shows only .csv files
OpenFile.Title = "Browse to file:" ' Title at the top of the dialog box
If OpenFile.ShowDialog() = DialogResult.OK Then ' Makes the open file dialog box show up
strFullPath = OpenFile.FileName ' Assigns variable
strFileName = Path.GetFileName(strFullPath)
If OpenFile.FileNames.Length > 0 Then ' Checks to see if they've picked a file
tbFile.Text = strFullPath ' Puts the filename in the textbox
' The connection string for reading into data connection form
Dim connStr As String
connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + Path.GetDirectoryName(strFullPath) + "; Extensions=csv,txt "
' Sets up the data set and gets stuff from .csv file
Dim Conn As New OdbcConnection(connStr)
Dim ds As DataSet
Dim DataAdapter As New OdbcDataAdapter("SELECT * FROM [" + strFileName + "]", Conn)
ds = New DataSet
Try
DataAdapter.Fill(ds, strFileName) ' Fills data grid..
DataGridView1.DataSource = ds.Tables(strFileName) ' ..according to data source
' Catch and display database errors
Catch ex As OdbcException
Dim odbcError As OdbcError
For Each odbcError In ex.Errors
MessageBox.Show(ex.Message)
Next
End Try
' Cleanup
OpenFile.Dispose()
Conn.Dispose()
DataAdapter.Dispose()
ds.Dispose()
End If
End If
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim cnn As SqlConnection
Dim connectionString As String
Dim sql As String
connectionString = "data source=Excel-PC\SQLEXPRESS;" & _
"initial catalog=NORTHWIND;Trusted_Connection=True"
cnn = New SqlConnection(connectionString)
cnn.Open()
sql = "SELECT * FROM [Order Details]"
Dim dscmd As New SqlDataAdapter(sql, cnn)
Dim ds As New DataSet
dscmd.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
cnn.Close()
End Sub
Private Sub ProductsDataGridView_CellFormatting(ByVal sender As Object,
ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
Handles DataGridView1.CellFormatting
If e.ColumnIndex = DataGridView1.Columns(3).Index _
AndAlso e.Value IsNot Nothing Then
'
If CInt(e.Value) < 10 Then
e.CellStyle.BackColor = Color.OrangeRed
e.CellStyle.ForeColor = Color.LightGoldenrodYellow
End If
'
End If
'
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim tblReadCSV As New DataTable()
tblReadCSV.Columns.Add("FName")
tblReadCSV.Columns.Add("LName")
tblReadCSV.Columns.Add("Department")
Dim csvParser As New TextFieldParser("C:\Users\Excel\Desktop\Employee.txt")
csvParser.Delimiters = New String() {","}
csvParser.TrimWhiteSpace = True
csvParser.ReadLine()
While Not (csvParser.EndOfData = True)
tblReadCSV.Rows.Add(csvParser.ReadFields())
End While
Dim con As New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
Dim strSql As String = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)"
'Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Connection = con
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName")
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName")
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department")
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
Dim result As Integer = dAdapter.Update(tblReadCSV)
End Sub
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Dim SQLConnectionString As String = "Data Source=Excel-PC\SQLEXPRESS;" & _
"Initial Catalog=Northwind;" & _
"Trusted_Connection=True"
' Open a connection to the AdventureWorks database.
Using SourceConnection As SqlConnection = _
New SqlConnection(SQLConnectionString)
SourceConnection.Open()
' Perform an initial count on the destination table.
Dim CommandRowCount As New SqlCommand( _
"SELECT COUNT(*) FROM dbo.Orders;", _
SourceConnection)
Dim CountStart As Long = _
System.Convert.ToInt32(CommandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count = {0}", CountStart)
' Get data from the source table as a AccessDataReader.
'Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
' "Data Source=" & "C:\Users\Excel\Desktop\OrdersTest.txt" & ";" & _
' "Extended Properties=" & "text;HDR=Yes;FMT=Delimited"","";"
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & "C:\Users\Excel\Desktop\" & ";" & _
"Extended Properties=""Text;HDR=No"""
Dim TextConnection As New System.Data.OleDb.OleDbConnection(ConnectionString)
Dim TextCommand As New OleDbCommand("SELECT * FROM OrdersTest#csv", TextConnection)
TextConnection.Open()
Dim TextDataReader As OleDbDataReader = TextCommand.ExecuteReader(CommandBehavior.SequentialAccess)
' Open the destination connection.
Using DestinationConnection As SqlConnection = _
New SqlConnection(SQLConnectionString)
DestinationConnection.Open()
' Set up the bulk copy object.
' The column positions in the source data reader
' match the column positions in the destination table,
' so there is no need to map columns.
Using BulkCopy As SqlBulkCopy = _
New SqlBulkCopy(DestinationConnection)
BulkCopy.DestinationTableName = _
"dbo.Orders"
Try
' Write from the source to the destination.
BulkCopy.WriteToServer(TextDataReader)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
' Close the AccessDataReader. The SqlBulkCopy
' object is automatically closed at the end
' of the Using block.
TextDataReader.Close()
End Try
End Using
' Perform a final count on the destination table
' to see how many rows were added.
Dim CountEnd As Long = _
System.Convert.ToInt32(CommandRowCount.ExecuteScalar())
'Console.WriteLine("Ending row count = {0}", CountEnd)
'Console.WriteLine("{0} rows were added.", CountEnd - CountStart)
End Using
End Using
'Dim FILE_NAME As String = "C:\Users\Excel\Desktop\OrdersTest.csv"
'Dim TextLine As String
'If System.IO.File.Exists(FILE_NAME) = True Then
' Dim objReader As New System.IO.StreamReader(FILE_NAME)
' Do While objReader.Peek() <> -1
' TextLine = TextLine & objReader.ReadLine() & vbNewLine
' Loop
'Else
' MsgBox("File Does Not Exist")
'End If
'Dim cn As New SqlConnection("Data Source=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;")
'Dim cmd As New SqlCommand
'cmd.Connection = cn
'cmd.Connection.Close()
'cmd.Connection.Open()
'cmd.CommandText = "INSERT INTO Orders (OrderID,CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry) values & OrdersTest.csv"
'cmd.ExecuteNonQuery()
'cmd.Connection.Close()
End Sub
Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click
' Define the Column Definition
Dim dt As New DataTable()
dt.Columns.Add("OrderID", GetType(Integer))
dt.Columns.Add("CustomerID", GetType(String))
dt.Columns.Add("EmployeeID", GetType(Integer))
dt.Columns.Add("OrderDate", GetType(Date))
dt.Columns.Add("RequiredDate", GetType(Date))
dt.Columns.Add("ShippedDate", GetType(Date))
dt.Columns.Add("ShipVia", GetType(Integer))
dt.Columns.Add("Freight", GetType(Decimal))
dt.Columns.Add("ShipName", GetType(String))
dt.Columns.Add("ShipAddress", GetType(String))
dt.Columns.Add("ShipCity", GetType(String))
dt.Columns.Add("ShipRegion", GetType(String))
dt.Columns.Add("ShipPostalCode", GetType(String))
dt.Columns.Add("ShipCountry", GetType(String))
Using cn = New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
cn.Open()
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
Dim currentRow As String()
Dim dr As DataRow
Dim sqlColumnDataType As String
reader = My.Computer.FileSystem.OpenTextFieldParser("C:\Users\Excel\Desktop\OrdersTest.csv")
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {","}
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
dr = dt.NewRow()
For currColumn = 0 To dt.Columns.Count - 1
sqlColumnDataType = dt.Columns(currColumn).DataType.Name
Select Case sqlColumnDataType
Case "String"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn))
End If
Case "Decimal"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = 0
Else
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn))
End If
Case "DateTime"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn))
End If
End Select
Next
dt.Rows.Add(dr)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid." & vbCrLf & "Terminating Read Operation.")
reader.Close()
reader.Dispose()
'Return False
Finally
dr = Nothing
End Try
End While
Using copy As New SqlBulkCopy(cn)
copy.DestinationTableName = "[dbo].[Orders]"
copy.WriteToServer(dt)
End Using
End Using
End Sub
Private Sub Button7_Click(sender As System.Object, e As System.EventArgs) Handles Button7.Click
'Dim cnn As SqlConnection
'Dim connectionString As String
'Dim sql As String
'connectionString = "data source=Excel-PC\SQLEXPRESS;" & _
'"initial catalog=NORTHWIND;Trusted_Connection=True"
'cnn = New SqlConnection(connectionString)
'cnn.Open()
'GetCsvData("C:\Users\Excel\Desktop\OrdersTest.csv", dbo.Orders)
End Sub
Public Shared Function GetCsvData(ByVal CSVFileName As String, ByRef CSVTable As DataTable) As Boolean
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
Dim currentRow As String()
Dim dr As DataRow
Dim sqlColumnDataType As String
reader = My.Computer.FileSystem.OpenTextFieldParser(CSVFileName)
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {","}
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
dr = CSVTable.NewRow()
For currColumn = 0 To CSVTable.Columns.Count - 1
sqlColumnDataType = CSVTable.Columns(currColumn).DataType.Name
Select Case sqlColumnDataType
Case "String"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn))
End If
Case "Decimal"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = 0
Else
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn))
End If
Case "DateTime"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn))
End If
End Select
Next
CSVTable.Rows.Add(dr)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid." & vbCrLf & "Terminating Read Operation.")
reader.Close()
reader.Dispose()
Return False
Finally
dr = Nothing
End Try
End While
reader.Close()
reader.Dispose()
Return True
End Function
Private Sub DataGridView1_RowValidating(ByVal sender As Object, ByVal e As DataGridViewCellCancelEventArgs)
End Sub
End Class
One more to try . . .
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim file As String = "Import.txt"
Dim path As String = "C:\Users\path_to_text_file\"
Dim ds As New DataSet
Try
If IO.File.Exists(IO.Path.Combine(path, file)) Then
Dim ConStr As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
path & ";Extended Properties=""Text;HDR=No;FMT=Delimited\"""
Dim conn As New OleDb.OleDbConnection(ConStr)
Dim da As New OleDb.OleDbDataAdapter("Select * from " & _
file, conn)
da.Fill(ds, "TextFile")
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
DataGridView1.DataSource = ds.Tables(0)
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
End Class

Checking data if exist in Database VB.Net

Imports System.Data.OleDb
Public Class Form1
Dim con As New OleDbConnection
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\sjmi.alfie\documents\visual studio 2010\Projects\Sample Ko\WindowsApplication4\MySample.accdb"
If con.State = ConnectionState.Closed Then
con.Open()
MsgBox("connection is open", vbInformation)
Else
MsgBox("connection is close", vbCritical)
End If
End Sub
Private Sub closeButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closeButton.Click
Me.Close()
End Sub
Private Sub regButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles regButton.Click
Dim strsql As String
Dim numrows As Integer
strsql = "SELECT COUNT(*) FROM Sample WHERE StudNo = " & TextBox1.Text & ""
Dim objcmd As New OleDbCommand(strsql, con)
numrows = objcmd.ExecuteScalar() <<<< Error "Data type mismatch in criteria."
If numrows > 0 Then
MsgBox("Record Exists", vbInformation, "Add")
Else
Dim myadapter1 As New OleDbDataAdapter("INSERT INTO [Sample] ([StudNo], [FirsName], [LastName]) VALUES ('" & TextBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "')", con)
Dim mytable1 As New DataTable
myadapter1.Fill(mytable1)
MsgBox("Success!!")
End If
con.Close()
End Sub
End Class
please help me. Thanks
Try this instead:
strsql = "SELECT COUNT(*) FROM Sample WHERE StudNo = ?"
Dim objcmd As New OleDbCommand(strsql, con)
objcmd.Parameters.AddWithValue("?", TextBox1.Text)
numrows = Convert.ToInt32(objcmd.ExecuteScalar())
It's called a "parameterized query", and it is the preferred way of doing what you intend.

Adding data to Access Database through Visual Basic Form

I have a forum where I want the user to type a profile name and then click Add and then it will add what they typed in the text box the the ProfileName field in my table. When I click the Add button, it comes up with an error that says An unhandled exception of type System.Data.OleDb.OleDbException occurred in system.data.dll. Here is my code:
Private Sub RefreshData()
Dim cnn As New OleDb.OleDbConnection
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT id AS [ID], " & _
"ProfileName AS [Name] " & _
" FROM Profile ORDER BY id", cnn)
Dim dt As New DataTable
da.Fill(dt)
cnn.Close()
Me.dgvData.DataSource = dt
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (TextBox1.Text = "") Then
MsgBox("Please enter a profile name.")
Else
Dim cnn As New OleDb.OleDbConnection("Provider=Microsof… Source=c:\Data\Database.mdb ;Extended Properties=Paradox 5.x;")
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO Profile(ProfileName) " & _
"VALUES (" & Me.TextBox1.Text & "')"
cmd.ExecuteNonQuery()
cnn.Close()
Dim oForm As addsnake
oForm = New addsnake
oForm.Show()
oForm = Nothing
Me.Close()
End If
End Sub
Without further information I suggest that:
You don't need to give id an alias of ID:
SELECT id AS [ID]
you might still enclose it in square-brackets though, if you like:
SELECT [id]
You are missing an apostrophe in the following line:
"VALUES (" & Me.TextBox1.Text & "')"
Also check your connection string at connectionstrings.com

How to permanently delete a record of database from VB

Im a beginner in VB and Im trying to delete a record from a database but it doesnt let me...
they gave me this error message which i do not fully understand what it meant...
or is there any other way to delete the record permanently?
Column named userID cannot be found.
Parameter name: columnName
Heres my codes
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class frmUserManagement
Dim countID As Integer = 0
Dim conn As New SqlConnection
Dim drEmployee As SqlClient.SqlDataReader
Dim cmdEmployee As New SqlClient.SqlCommand
Dim sAdapter As New SqlDataAdapter
Dim sTable As New DataTable
Private Sub btnAddEmp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddEmp.Click
Dim tranEmployee As SqlClient.SqlTransaction
sAdapter = New SqlDataAdapter(cmdEmployee)
Dim strID As String
Dim strName As String
Dim strPosition As String
Dim strContactNo As String
Dim strAddress As String
Dim strDOB As String
Dim strGender As String
Dim strSQL As String
conn.Open()
strID = lblEmpID.Text
strName = txtEmpName.Text
strPosition = cboEmpPosition.Text
strContactNo = mskEmpDOB.Text
strDOB = mskEmpDOB.Text
strAddress = txtEmpAddress.Text
If radEmpMale.Checked Then
strGender = "Male"
Else
strGender = "Female"
End If
strSQL = "INSERT INTO Users(userID,userName,userPosition,userGender,userDOB,userAddress)" & _
"VALUES(#ID,#NAME,#POSITION,#GENDER,#DOB,#ADDRESS)"
tranEmployee = conn.BeginTransaction()
With cmdEmployee
.Transaction = tranEmployee
.CommandText = strSQL
.Parameters.AddWithValue("#ID", strID)
.Parameters.AddWithValue("#NAME", strName)
.Parameters.AddWithValue("#POSITION", strPosition)
.Parameters.AddWithValue("#GENDER", strGender)
.Parameters.AddWithValue("#DOB", strDOB)
.Parameters.AddWithValue("#ADDRESS", strAddress)
.Connection = conn
End With
Try
cmdEmployee.ExecuteNonQuery()
tranEmployee.Commit()
Catch ex As Exception
tranEmployee.Rollback()
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try
End Sub
Private Sub frmUserManagement_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If mintIndex <= 9000 Then
lblEmpID.Text = "EMP" & (countID + 1).ToString("000#")
End If
Try
With conn
.ConnectionString = strConnection
.Open()
End With
With cmdEmployee
.CommandText = "SELECT * FROM Users ORDER BY userID"
.Connection = conn
End With
drEmployee = cmdEmployee.ExecuteReader()
If drEmployee.HasRows Then
While drEmployee.Read()
DataGridView1.Rows.Add(drEmployee(0), drEmployee(3), drEmployee(1), drEmployee(4), drEmployee(2), drEmployee(5))
End While
drEmployee.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try
End Sub
Private Sub btnDeleteEmp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteEmp.Click
With cmdEmployee
.CommandText = "DELETE FROM Users WHERE userID = " & DataGridView1.CurrentRow.Cells(0).Value & ""
.Connection = conn
.Parameters.AddWithValue("#ID", 0)
End With
Dim rows = DataGridView1.SelectedRows
For Each row In rows
cmdEmployee.Parameters("#ID").Value = row.Cells("userID").Value
cmdEmployee.ExecuteNonQuery()
Next
drEmployee = cmdEmployee.ExecuteReader()
End Sub
Private Sub btnEditEmp_Click(sender As System.Object, e As System.EventArgs) Handles btnEditEmp.Click
lblEmpID.Enabled = False
txtEmpName.Enabled = False
grpGender.Enabled = False
End Sub
End Class
It means you do not have a column named userID in your table, are you sure it's not just ID?
You should use:
With cmdEmployee
.CommandText = "DELETE FROM Users WHERE userID = #ID"
.Connection = conn
.Parameters.AddWithValue("#ID", 0)
End With

Resources