viewdata.Visible = True
Dim a As String = fromdtp.Value.ToString("MM/dd/yyyy")
Dim b As String = Todtp.Value.ToString("MM/dd/yyyy")
Dim type As String = sel.SelectedItem.ToString()
If sel.SelectedItem.ToString = "allitems" Then
Dim searchQuery As String = "SELECT * From entry where delivery between '" & a & "' and '" & b & "' "
MessageBox(searchQuery)
Dim cmd As New SqlCommand(searchQuery, con)
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
viewdata.DataSource = table
Else
Dim searchQuery As String = "SELECT * From entry where p_name='" & type & "' and delivery between '" & a & "' and '" & b & "' "
MessageBox(searchQuery)
Dim cmd As New SqlCommand(searchQuery, con)
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
viewdata.DataSource = table
End If
Form3.Show()
fromdtp.Value = Date.Now
Todtp.Value = Date.Now
this is my form code after clicking the button i want to generate a report depend on the query
And i want to load data from Sqlserver to Crystal Report in VB.net
How can I convert a row data into string or text and display it into a label? My problem is when I click on my login button which contains the SQL code that gains a row data into alabel, the result in my label is false. not the text. How can I convert it into string?
Here's my code:
Private Sub cmdLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLog.Click
Dim connection As New SqlClient.SqlConnection
Dim command As New SqlClient.SqlCommand
Dim adaptor As New SqlClient.SqlDataAdapter
Dim dataset As New DataSet
Dim reader As MySqlDataReader = Nothing
Dim sapi
sapi = CreateObject("sapi.spvoice")
connection.ConnectionString = ("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Calupad\Desktop\HTF feat Yiyet\HTF feat Yiyet\Database1.mdf;Integrated Security=True;User Instance=True")
command.CommandText = "SELECT * FROM [Users] WHERE Username='" & txtUser.Text & "' AND Password ='" & txtPass.Text & "';"
txtWel.Text = "Welcome Back, " + txtUser.Text + "!....."
connection.Open()
command.Connection = connection
adaptor.SelectCommand = command
adaptor.Fill(dataset, "0")
txtStat.text = command.CommandText = "SELECT Status FROM [Users] WHERE Username = '" & txtUser.Text & "' ".ToString
txtStat.Text = stat
Dim count = dataset.Tables(0).Rows.Count
If count > 0 Then
MsgBox("Login Successful!" & vbNewLine & txtStat.Text, MsgBoxStyle.Information, "Access Granted")
sapi.speak(txtWel.Text)
Me.Hide()
Form1.Show()
frmMenu.Show()
txtUser.Clear()
txtPass.Clear()
tries = 3
Else
ctr = tries - 1
tries = ctr
sapi.speak(txtUser.Text + txtNot.Text)
MsgBox("Invalid Account!" + vbNewLine + "Attempts Remaining: " & tries, vbCritical, "Access Denied")
txtUser.Clear()
txtPass.Clear()
If tries = 0 Then
MsgBox("You've reached the maximum attempts!" + vbNewLine + "The program will be terminated.", vbCritical, "Terminated!")
Me.Close()
End If
End If
End Sub
First of all, the way you check for username and password is weak and is most certainly volnurable to SQL injections. You are checking if the 'count' of rows is greater than zero then the user has logged in successfully, where as you should only compare count to 1. and instead of counting the rows, try to compare the row values to what the user has input in the username and passoword fields and what is returned from the database rows.
The "hacker" can simply type this and he will be allowed to log in according to the logic of your code:
You just need to retrieve the data stored into dataset variable that you filled using the adapter.
Assuming your database table contains fields like First_Name and 'Last_Name', here is how you can display them on any label control on your form:
adaptor.Fill(dataset, "0")
myFirstName.Text = dataset.Tables(0).Rows(0).Item("First_Name").ToString()
myLastName.Text = dataset.Tables(0).Rows(0).Item("First_Name").ToString()
You can also retrieve the column without having to know its name like this
myLabel.text = = dataset.Tables(0).Rows(0).Item(3).ToString()
'This will retrieve the 4th column from the table (zero based array)
You can also clean up your code by declaring a variable to hold the retrieved table
adaptor.Fill(dataset, "0")
Dim myTable as DataTable = dataset.Tables(0)
myFirstName.Text = myTable.Rows(0).Item(0).ToString()
Hope this helps
i'm a newbye I have a problem with the vba code to import data from a table in excel file access. Using Office 2010, but the launch of the code gives me an error:
(translate from Italian)
run-time error -2147217865 (80040e37) Microsoft Access Database engine cannot find object 'INCONTRI$A1:I108468.
Make sure the object exists and that its name and the path you typed BE CORRECTED.
HERE IS THE CODE:
VB:
Sub EXPORT2ACCESS()
Dim ultimariga As Long
Dim ultimacolonna As Integer
Dim foglio, finesel As String
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\TOTALBET\TOTALBET_XML_DB.accdb"
dbWb = Application.ActiveWorkbook.FullName
For i = 1 To 4
ultimariga = Sheets(i).Range("A" & Rows.Count).End(xlUp).Row
ultimacolonna = Sheets(i).Cells(1, Sheets(i).Columns.Count).End(xlToLeft).Column
finesel = Application.ConvertFormula("R" & ultimariga & "C" & ultimacolonna, xlR1C1, xlA1, toAbsolute:=xlRelative)
foglio = Application.Sheets(i).Name
Set cn = CreateObject("ADODB.Connection")
Dim cmd As ADODB.Command
dsh = "[" & Application.Sheets(i).Name & "$A1:" & finesel & "]"
cn.Open strCon
Set cmd = New ADODB.Command
cmd.CommandType = adCmdText
cmd.CommandText = "Delete * from " & foglio
cmd.ActiveConnection = cn.ConnectionString
cmd.Execute
With Sheets(i)
For x = 1 To ultimacolonna
campo = "[" & .Cells(1, x).Value & "]"
If x = 1 Then
stringa = campo
Else
stringa = stringa & ", " & campo
End If
Next x
End With
''Insert into a table called
strsql = "INSERT INTO " & foglio & "(" & stringa & ") "
strsql = strsql & "SELECT * FROM [Excel 12.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
Debug.Print strsql
''Execute the statement
cn.Execute strsql
Next i
End Sub
the table "incontri" exists in my excel file and contain data. same sub worked for other sheets without problems and insert data in access table.
string that pass to exceute is:
VB:
INSERT INTO INCONTRI([Static_ID], [Stage_ID], [Season], [Number], [Data], [Time], [Status], [Venue_ID], [League]) SELECT * FROM [Excel 12.0;HDR=YES;DATABASE=C:\Users\Admin\Desktop\test xml.xlsm].[INCONTRI$A1:I108468]
Here is files (too big to put in forum, sorry:
Excel file with code and data: https://www.sugarsync.com/pf/D9350024_63096411_117675
Access file: https://www.sugarsync.com/pf/D9350024_63096411_117635
I'm going crazy to understand where the error is please help!
Thanks in advance to all the people who want to help me figure out where I'm wrong.
greetings
Vincent
You will probably find it easier to do this from Access. Access uses VBA like Excel, so you shouldn't have much trouble with it.
In Access, there's a command called DoCmd.TransferText. Click here for the full syntax.
Do a search for more examples. Good luck.
I have the following array that contains ticker symbols: Public Shared tickerArray() As String = {"GOOG", "AAPL", "V", "MSFT"}. I need to use this loop: For Each tickerValue In Form1.tickerArray to load the csv file for each ticker symbol into one large table in Microsoft Access. The csv files are located at "http://ichart.yahoo.com/table.csv?s=" & tickerValue. I also need the respective ticker symbol to be loaded into each line of the table that is imported from the csv file in order to make each line unique. So the columns in the database should be: "Ticker, Date, Open, High, Low, Close, Volumne & Adj Close".
I've found information about loading a local csv file into Access but I can't seem to figure out how to load csv files from the internet into Access through vb.net.
Also, I will need to update this table frequently so I need to only insert new unique lines from the csv file. No duplicates.
Any suggestions? Thanks!
UPDATE:
Here is the code I have so far.
Imports System.Data
Imports System.Data.OleDb
Imports System.Net
Imports System.IO
Public Class Form1
Public Shared tickerArray() As String = {"GOOG", "AAPL", "V", "MSFT"}
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim myConnection As OleDbConnection
Dim DBpath As String =
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
myConnection = New OleDbConnection(sConnectionString)
myConnection.Open()
Dim strURL As String
Dim strBuffer As String
For Each tickerValue In Form1.tickerArray
'Creates the request URL for Yahoo.
strURL = "http://ichart.yahoo.com/table.csv?s=" & tickerValue
strBuffer = RequestWebData(strURL)
'Create array.
Dim sReader As New StringReader(strBuffer)
Dim List As New List(Of String)
Do While sReader.Peek >= 0
List.Add(sReader.ReadLine)
Loop
Dim lines As String() = List.ToArray
sReader.Close()
For Each Line In lines.Skip(1)
MsgBox(Line)
Dim myInsert As String = TextToInsert(Line, tickerValue)
Dim cmd As New OleDbCommand(myInsert, myConnection)
cmd.ExecuteNonQuery()
Next
Next
End Sub
Function TextToInsert(ByVal inputString As String, ByVal ticker As String)
Dim Dt As String = inputString.Split(",")(0).Trim
Dim Open As String = inputString.Split(",")(1).Trim
Dim High As String = inputString.Split(",")(1).Trim
Dim Low As String = inputString.Split(",")(1).Trim
Dim Close As String = inputString.Split(",")(1).Trim
Dim Volume As String = inputString.Split(",")(1).Trim
Dim Adj_Close As String = inputString.Split(",")(1).Trim
Dim SQLstr As String
SQLstr = "INSERT INTO Historical (Ticker, Date, Open, High, Low, Close, Volume, Adj Close) " & "VALUES (" & "'" & ticker & "','" & Dt & "','" & Open & "','" & High & "'," & "'" & Low & "','" & Close & "','" & Volume & "','" & Adj_Close & "'" & ")"
Return SQLstr
End Function
Private Function RequestWebData(ByVal pstrURL As String) As String
Dim objWReq As WebRequest
Dim objWResp As WebResponse
Dim strBuffer As String
'Contact the website
objWReq = HttpWebRequest.Create(pstrURL)
objWResp = objWReq.GetResponse()
'Read the answer from the Web site and store it into a stream
Dim objSR As StreamReader
objSR = New StreamReader(objWResp.GetResponseStream)
strBuffer = objSR.ReadToEnd
objSR.Close()
objWResp.Close()
Return strBuffer
End Function
End Class
I get error code "OleDBException was unhandled. Syntax error in INSERT INTO statement." at line cmd.ExecuteNonQuery() Please help!
you may use the System.Data.OleDb Namespace to define function to make insert into the db.
Something like (in a very rough way):
Dim myConnection As OleDbConnection
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
myConnection = New OleDbConnection(sConnectionString)
myConnection.Open()
Then make a cycle on each line in the csv
Dim myInsert as String= functionTextToInsert(inputString)
Dim cmd As New OleDbCommand(myInsert, myConnection)
cmd.ExecuteNonQuery()
The functionTextToInsert(ByVal inputString as string) is a function that converts a line from the csv in a insert string: "max;min;vol" -> "Insert into MYTABLE (Column_01,Column_02,Column_03) VALUES (max,min,vol);"
Try this:
Writing large number of records (bulk insert) to Access in .NET/C#
I've never worked with DAO, so I can't be much help here, but...
if this MSSQL syntax works on MS ACCESS, use a command object and pass it a parameter containing your csv as a varchar(max), or similar access data type, which will the content of the CSV from your app:
BULK
INSERT mytable
FROM #myCSVstring
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO
Two things, the SO post states that DAO is a lot faster, and your terminators may be different, but I'd start with these.
I think the previous answers are unnecessarily complicated. All you need to do it send an XMLHTTP request. That fetches the CSV data as a string, which can then be parsed into a table.
Below is a VBA subroutine that does that. Documentation of where I found the techniques is in the code comments. I've run this in Access 2019, and it works.
The modifications of the data indicated in the question can be performed before or after inserting the data into the table.
Sub pImportOnlineCsvAsTable(sURL As String, sTableName As String, Optional sKey As String)
' Download a CSV file from the Internet and parse it into an Access table (all strings).
' Adapted from "www.stackoverflow.com/questions/52142757/vba-download-csv-from-a-link/#52175815"
' This shows how to download an online CSV file into an ADO stream, then save it as a local file.
' and "www.stackoverflow.com/questions/33860833/convert-adodb-binary-stream-to-string-vba/#33883789"
' This shows I don't need the stream, but can use the CSV data as a string and parse it into a table.
' Documentation on "XMLHTTP" object:
' "https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms760305(v=vs.85)"
Dim oWinHttpReq As Object
Dim oDB As Database
Dim sSQL As String, sCSVdata As String, _
asCSVrows As Variant, asCSVfields As Variant, _
nCSVrows As Long, nCSVfields As Integer, _
nCountRows As Long, nCountFields As Integer
Set oDB = CurrentDb()
Set oWinHttpReq = CreateObject("Microsoft.XMLHTTP")
oWinHttpReq.Open "get", sURL, False
oWinHttpReq.send
If oWinHttpReq.status = 200 Then
sCSVdata = oWinHttpReq.ResponseText
asCSVrows = Split(sCSVdata, Chr(10))
nCSVrows = UBound(asCSVrows) + 1
asCSVfields = Split(asCSVrows(0), ",")
nCSVfields = UBound(asCSVfields) + 1
sSQL = ""
For nCountFields = 0 To (nCSVfields - 1)
sSQL = sSQL & "[" & asCSVfields(nCountFields) & "] varchar(255)" & _
IIf(nCountFields = nCSVfields - 1, "", ", ")
Next
sSQL = "create table [" & sTableName & "] (" & sSQL & ");"
oDB.Execute (sSQL)
For nCountRows = 1 To (nCSVrows - 1)
asCSVfields = Split(asCSVrows(nCountRows), ",")
sSQL = ""
For nCountFields = 0 To (nCSVfields - 1)
sSQL = sSQL & """" & asCSVfields(nCountFields) & """" & _
IIf(nCountFields = nCSVfields - 1, "", ", ")
Next
sSQL = "insert into [" & sTableName & "] values (" & sSQL & ");"
oDB.Execute (sSQL)
Next
If sKey <> "" Then _
oDB.Execute "alter table [" & sTableName & "] add primary key ([" & sKey & "]);"
End If
Set oWinHttpReq = Nothing
Set oDB = Nothing
End Sub ' pImportOnlineCsvAsTable()
I have a desktop application using vb.net, to process some excel files, those files are stored in a sql server database.
Here is the code I have:
Try
conDCS.Open()
comDCS.Connection = conDCS
comDCS.CommandType = CommandType.Text
comDCS.CommandText = "select top 2 [Filename], [File] " & _
"from tblFiles (nolock) " & _
"where ([Filename] like 'DIG%' or [Filename] like 'FAC%') and " & _
"(UploadDate>='" & FromDate & "' and UploadDate<'" & ToDate & "')"
comDCS.ExecuteNonQuery()
rdrDCS = comDCS.ExecuteReader
If rdrDCS.HasRows Then
While rdrDCS.Read
Dim imageInBytes As Byte() = rdrDCS(1)
Dim memoryStream As System.IO.MemoryStream = New System.IO.MemoryStream(imageInBytes, False)
Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(memoryStream)
image.Save(TempPath & rdrDCS(0))
End While
ToProcess = True
End If
rdrDCS.Close()
Catch ex As Exception
ToProcess = False
MessageBox.Show("Error accessing to the files: " & ex.Message)
Finally
conDCS.Close()
End Try
I'm getting: "Parameter is not valid" in this line:
Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(memoryStream)
I have understood that this error is related to an invalid image data, but I can't figure it out what could be the problem.
imageInBytes has a length of 41473. And some items of the array have zero as value.
What could be wrong here, or perhaps, can anyone supply a working code to achieve this?
We use a common method to save a file from a database field to a file:
Public Function FieldToFile(ByVal sFileName As String, ByVal theField As Object) As Boolean
' Exceptions are handled by the caller
If theField IsNot DBNull.Value Then
Using oStream As New System.IO.FileStream(sFileName, IO.FileMode.Create, IO.FileAccess.Write)
If oStream IsNot Nothing Then
Dim aBytes As Byte()
aBytes = DirectCast(theField, Byte())
oStream.Write(aBytes, 0, aBytes.Length)
oStream.Close()
End If
End Using
End If
Return True
End Function
This can be called as follows:
Call FieldToFile(someFileName, rdrDCS(1)