Parsing textfile to access database in VB.NET - vb.net-2010

I am trying to store the information from text file into the database. This is what I have but could not figure out what to do next.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim filename As String
filename = Application.StartupPath + "\darsReport.txt"
Dim iofile As New StreamReader(filename)
If File.Exists(filename) Then
Dim ioline As String
Dim ID, studentName, currentGPA, ReqGPA, expectedGraduation
ioline = iofile.ReadLine
While Not ioline = ""
Dim mysplit = Split(ioline, " ")
ID = mysplit(1)
studentName = mysplit(0)
expectedGraduation = mysplit(2)
currentGPA = mysplit(3)
ReqGPA = mysplit(4)
End While
Else
MsgBox(filename + "Does not exist.")
End If
End Sub
End Class

After this you need to run an INSERT query on your database table. The simplest way to do that is to use SqlCommand class (assuming that you have a SQL Server database):
Dim con as new SqlConnection("Your Connection String Here")
con.Open()
Dim cmd as New SqlCommand("", con)
cmd.CommandText = String.Format("INSERT INTO [YourTable](ID, Name, CurrentGPA) VALUES({0}, '{1}', {2})", ID, studentName, currentGPA)
cmd.ExecuteNonQuery()
con.Close()
Use this code block inside your loop and all your rows will be inserted into the database. However note that this is really the very basic way of doing it and a lot more code should be written to properly handle exceptions, invalid data etc. Also this method can easily be exploited using SQL Injections. Far better apporaches exist in .NET (e.g. DataSets and Entity Framework) that should rather be used for this task.

Related

How do i get the data to my database using vb.net (class, module and form)

I hope the title is enough to understand my problem, I already installed whats need to run the ADO.NET, I already have a connection string in my module and data query in my class,
Imports System.Data
Imports System.Data.OleDb
Module GlobalVariables
Public sGlobalConnectionString As String
Friend conString As String
Public dr As OleDbDataReader
Sub Main()
Dim sGlobalConnectionString As New OleDb.OleDbConnection
Dim sDataserver As String
Dim sDatabaseName As String
Dim sDatabaseConnection As String
sDataserver = "localhost"
sDatabaseName = "employee"
sDatabaseConnection = "Driver={MariaDB ODBC 3.1 Driver}; SERVER=" & sDataserver & "; UID=root;PWD=******; Database=" & sDatabaseName & "; PORT=3307; OPTION=3"
sGlobalConnectionString = New OleDb.OleDbConnection(conString)
End Sub
End Module
this is my class
Imports System.Data.OleDb
Public Class clsDataQuery
Public Shared Sub Class_initialize()
Dim con = New OleDb.OleDbConnection
con.ConnectionString = sGlobalConnectionString
con.Open()
End Sub
Public Shared Sub Class_Terminate()
Dim con = New OleDb.OleDbConnection
If Not con Is Nothing Then
con.Close()
con = Nothing
End If
End Sub
Public Function GetRecordDataSet(ByVal sStoreProcName As String, ByVal sParameterList As String)
Dim cmd As New OleDbCommand()
Dim arrParameter, arrParamName
Dim sParamName As String
Dim sDataValue
Dim lCtr As Long
On Error GoTo errhandler
cmd.Connection = New OleDb.OleDbConnection
cmd.CommandTimeout = 1800
cmd.CommandText = CommandType.Text
If Not Trim(sParameterList) = "" Then
arrParameter = Split(sParameterList, "|", , vbTextCompare)
If UBound(arrParameter) >= 0 And IsArray(arrParameter) Then
For lCtr = 0 To UBound(arrParameter)
arrParamName = Split(arrParameter(lCtr), "$", , vbTextCompare)
sParamName = arrParamName(0)
sDataValue = arrParamName(1)
cmd.Parameters.Item(sParamName) = sDataValue
Next lCtr
End If
End If
GetRecordDataSet = cmd.ExecuteReader
cmd = Nothing
Exit Function
errhandler:
MessageBox.Show("Records Not Found!!!")
End Function
End Class
if this button is click, the value of Textbox1.text will search in the database if it is exist, if exist it will continue into another form if not error message will appear, how do i do that?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim username = txtbox_lastname.Text
If username <> "" Then
Try
clsDataQuery.Class_initialize()
Catch ex As Exception
MessageBox.Show("No Record Found")
End Try
Else
MessageBox.Show("No Record Found!!!")
End If
End Sub
If this is MariaDb then you want to use the provider for MySql. Not ODBC and not OleDb. No wonder you are having problems. There is not much information available for this database compared to the usual Access database used for beginners.
Do not declare database objects anywhere but the method they are used in. You can declare a Private variable for the connection string at the class level.
Although one of these is a Module level variable and one is a local variable, it is very confusing and bad practice. Why would you call a connection object a String?
Public sGlobalConnectionString As String
Dim sGlobalConnectionString As New OleDb.OleDbConnection
BTW, it is fine to declare and initialize your variables in a single line.
Dim sDataserver = "localhost"
You create a new connection on the first line of Sub Main, then you throw it away and create another new connection on the last line. Since sDataServer and sDatabaseName are hard coded why not just put the literal values directly into the connection string.
After all that you pass conStr to the constructor of the connection instead of sDatabaseConnection. Why were you building sDatabaseConnection (another misnomer, it is not a connection, its a string) and then never use it. Has conStr been set elsewhere?
At any rate, throw out the whole module.
Moving on to your DataQuery class. First, the name should begin with an upper case letter.
Get rid of Class_initialize. We don't want to create or open any connection except in the method where it is used. You never call Class_Terminate so dump that too.
The GetRecordDataSet method...
Functions in vb.net require a datatype. The old VB6 syntax of assigning the return value to the name of the function will work but it is not the .net way. In vb.net we use the Return keyword.
You have not initialized or given a datatype to arrParameter, arrParamName or sDataValue which violates Option Strict. (You do have Option Strict On, don't you?)
On Error GoTo errhandler is a sad leftover from VB6. .net languages have structured error handling with Try...Catch...Finally...End Try.
cmd.Connection = New OleDb.OleDbConnection sets the connection property however this new connection has no connection string.
cmd.CommandText = CommandType.Text Now this is just silly. What I think you want is cmd.CommandType =CommandType.StoredProcedure
Using...End Using blocks take care of declaring, closing and disposing database objects even if there is an error. You don't want to return a DataReader because a reader requires an open connection. cmd.ExecuteReader returns a DataReader. I used the reader to load a DataTable and returned the DataTable.
It seems you are trying to develop a factory pattern but it is way too advanced for your. Just pass value and call a method specific to what your are searching for. You want your DataQuery code to be independent from your user interface. The Button code doesn't care where the data is coming from. It could be a database, a text file, or a web service. Likewise the DataQuery code doesn't know where the values are coming from. It could be a WinForms app, a web application or a phone app.
Public Class DataQuery
Private Shared ConStr As String = "server=localhost;userid=root;database=employee"
Public Shared Function SearchByLastName(ByVal LName As String) As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConStr),
cmd As New MySqlCommand("Select * From PutTableNameHere Where LastName = #LName", cn)
cmd.Parameters.Add("#LName", MySqlDbType.VarChar).Value = LName
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
End Class
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dt As DataTable = Nothing
If txtbox_lastname.Text <> "" Then
Try
dt = DataQuery.SearchByLastName(txtbox_lastname.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If
DataGridView1.DataSource = dt
End Sub
Before answering, I really think that the GetRecordDataSet() at the very least a darn good tidy up, better yet removed from history
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim username = txtbox_lastname.Text
If username <> "" Then
Try
clsDataQuery.Class_initialize()
Dim reader = GetRecordDataSet("storedProcName", txtbox_lastName.Text)
Do While reader.Read()
'Process record etc
Loop
Catch ex As Exception
MessageBox.Show("No Record Found")
End Try
Else
MessageBox.Show("No Record Found!!!")
End If
End Sub
Might be a bit rough, but should get you heading in the right direction

OleDbException was unhandled, syntax error in WHERE clause?

Having trouble with a persistent error. My form allows the user to see a list of elements in a particular group. The input for group number is a combobox called groupbox and the output is a combobox called ElementResults. I am getting the error on the line: GroupSearch.ExecuteNonQuery()
Imports System.Data.OleDb
Public Class ElementsSearch
Public Shared connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\A\My Documents\Visual Studio 2010\Projects\A2\Element.accdb;Persist Security Info=False;"
Public Shared ElementsTable
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim Search As New OleDbConnection(connectionString)
Search.Open()
Dim SearchCriteria As String
SearchCriteria = Groupbox.Text
Dim query As String = "SELECT * From ElementsTable WHERE Group='" & SearchCriteria & "'"
Dim GroupSearch As New OleDbCommand(query, Search)
GroupSearch.ExecuteNonQuery()
Dim reader As OleDbDataReader = GroupSearch.ExecuteReader()
ElementResults.Text = Convert.ToString(reader("Name"))
End Sub
End Class
You define the field group which is a reserved keyword.
Try [group] instead like in this sample:
SELECT * From ElementsTable WHERE [Group]='aaa'
To avoid all the errors you're getting, consider changing your code to something like this:
Using connection As New OleDbConnection(connectionString)
connection.Open()
Using command As New OleDbCommand("SELECT * From ElementsTable WHERE [Group]=#Group", connection)
command.Parameters.AddWithValue("#Group", SearchCriteria)
Using reader As OleDbDataReader = command.ExecuteReader()
Do While reader.Read()
ElementResults.Text = reader.GetString("Name")
Loop
End Using
End Using
End Using

Why i can not use string dataType as input argument in webmethod in vb.net

i implemented a webservice with vb.net
method is like this
Public Class WebService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function INSERT_NEW(ByVal i As Integer, ByVal f As String) As String
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Try
con.ConnectionString = ConfigurationManager.ConnectionStrings("WebConnectionSTR").ToString
'Dim strMdbPath As String = "C:\Users\Hossein\Documents\Visual Studio 2010\WebSites\WebSite1\"
'Dim strProvider As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
'Dim strDBFile As String = "db.mdb"
cmd.Connection = con
cmd.CommandText = "insert into tb values (" & i & ",'" & f & "')"
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Return "1"
Catch ex As Exception
con.Close()
Return "0"
End Try
End Function
End Class
it works if i run it and invoke it
but when i create a windows application i occured with an unkown problem
because i used 2 (integer and string) input parameters in web method as input parameters,
INSERT_NEW(byval i as integer,byval f as string) as string
it didnt work
Imports wsdl.Myservice
Public Class Form1
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim s As WebServiceSoap = New WebServiceSoapClient
lblAdd.Text = s.INSERT_NEW(txt1.Text, txt2.Text)
End Sub
End Class
but when i change the input argument in web method to INTEGER it works properly
is it a limitation to use data types in web method in web service OR i did something wrong???
i added these 3 photos to show you the exact error that i get.
You declare your webmethod to receive an Integer and a String. So you should pass an Integer and a String, but your code tries to pass two strings. You should respect the signature of the webmethod and pass the parameters as expected
lblAdd.Text = s.INSERT_NEW(Convert.ToInt32(txt1.Text), txt2.Text)
Of course, here I am assuming that the string in txt1.Text is convertible in an integer.
Said that I wish to point your attention to a very big problem of your code:
What happen if a malicious user pass for the parameter f the following string
"xxxxx');DELETE FROM tb; --"
It is called Sql Injection and could wreak havoc with your database. Try to use ALWAYS a parameterized query when you receieve input from your users and pass it to a database command
Using con = New OleDbConnection(ConfigurationManager.ConnectionStrings("WebConnectionSTR").ConnectionString)
Using cmd = New OleDbCommand("insert into tb values (?, ?)", con)
Try
con.Open()
cmd.Parameters.AddWithValue("#p1",i)
cmd.Parameters.AddWithValue("#p2",f)
cmd.ExecuteNonQuery()
Return "1"
Catch ex As Exception
Return "0"
End Try
End Using
End Using
Finally i found the answer myself
Imports wsdl.Myservice
Imports System.Reflection
Public Class Form1
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim s As WebServiceSoap = New WebServiceSoapClient
Dim method As MethodInfo = s.GetType().GetMethod("INSERT_NEW")
Dim returnValue As Integer = method.Invoke(s, New Object() {CInt(txt1.Text), txt2.Text})
lblAdd.Text = returnValue
End Sub
End Class

Reading tables using OleDBConnection

First off, i'm new to VB and this is my first project using OleDBConnection.
ok, so i'm trying to the most simple thing using oleDbConnection (i assume). I just want to read data from a table in the Access DB and display that information to dropboxes (or anything) in my winForm.
Public Class QueManger
Dim dbConnection As OleDbConnection
Dim dbCommand As OleDbCommand
Dim dbDataAdapter As OleDbDataAdapter
Dim ConnectString As String = "Provider = Microsoft.Jet.OLEDB.4.0;" & "Data Source = \\atrts10\F:\Applications\ATRTaxCert\Development\mtaylor\TaxCert_be_test.accdb"
Dim dtMain As DataTable
Private Sub QueManger_Load(sender As Object, e As EventArgs) Handles MyBase.Load
StatusName()
End Sub
Private Sub StatusName()
Dim taxconn As OleDbConnection
Try
taxconn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\atrts10\F:\Applications\ATRTaxCert\Development\mtaylor\TaxCert_be_test.accdb")
Dim taxcmd As OleDbCommand = taxconn.CreateCommand
taxcmd.CommandText = "SELECT StatusName FROM Status ORDER BY StatusName"
Dim rdr2 As OleDbDataReader
If taxconn.State = ConnectionState.Closed Then
taxconn.Open()
End If
rdr2 = taxcmd.ExecuteReader
'boxStatus.Items.Add("All")
While rdr2.Read()
boxClient.Items.Add(rdr2.Item("StatusName"))
End While
Catch ex As Exception
Finally
taxconn.Close()
End Try
End Sub
The error comes when it tries to run the "taxconn.Open()" function.
The error says "The Microsoft Access database engine cannot open or write to the file '\atrts10\F:\Applications\ATRTaxCert\Development\mtaylor\TaxCert_be_test.accdb'. It is already opened exclusively by another user, or you need permission to view and write its data."
any thoughts?
try to close the opened table first in access if you are editing them, and try to add "#" before the string to use your path.
then try to use this connection string;
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + yourDataBasePath + ";Persist Security Info=False;";

ExecuteReader CommandText property has not been properly initialized

First of all sorry if some of the code isn't right. I'm still new to using sql on vb.net
I have the following code:
Imports MySql.Data.MySqlClient
Imports System.Data.SqlClient
Public Class Form1
Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click
Dim objConn As MySqlConnection
Dim objDataset As New DataSet
Dim objDataAdapter As MySqlDataAdapter
Dim myCommand As MySqlCommand
Dim sqlConn As String
objConn = New MySqlConnection("server=localhost;userid=root;database=attendance_system")
myCommand = objConn.CreateCommand
objConn.Open()
Dim objReader As MySqlDataReader = myCommand.ExecuteReader
sqlConn = "SELECT student_name FROM profile"
objDataAdapter = New MySqlDataAdapter(sqlConn, objConn)
objDataAdapter.Fill(objDataset, "profile")
MsgBox("The Connection is Now 'OPEN'")
objReader.Read()
TextBox1.Text = objReader("student_name")
objReader.Close()
objConn.Close()
End Sub
End Class
I am using MySQL connector via vb.net in phpmyadmin and have set a database with records.
The connection string is working, but my problem is when I try to click the button to load the data in the textbox, I keep getting:
The CommandText property has not been properly initialized."
The error is on this line:
"Dim objReader As MySqlDataReader = myCommand.ExecuteReader"
I've tried a lot of fixes that I've found on this site and the others as well.
This is the problem:
Dim objReader As MySqlDataReader = myCommand.ExecuteReader
sqlConn = "SELECT student_name FROM profile"
You're declared the SQL after you've tried executing the query (and even then you don't set it as the SQL for the command). How would you expect that to work? Additionally, sqlConn is a very strange name for a variable declaring the SQL - I'd expect it to be a connection.
It looks like you're trying to mix too very different ways of fetching data:
Reading directly from the reader
Filling a DataSet with a data adapter
You shouldn't be mixing them like that. Work out which you actually want to do, take out all the code related to the other style, and then make sure you're doing everything in a sensible order.
From MySqlCommand Class and the example given as
Public Sub ReadMyData(myConnString As String)
Dim mySelectQuery As String = "SELECT * FROM Test.Dept"
Dim myConnection As New MySqlConnection(myConnString)
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As MySqlDataReader = myCommand.ExecuteReader()
Try
While myReader.Read()
Console.WriteLine(myReader.GetInt32(0).ToString() + ", " _
+ myReader.GetString(1))
End While
Finally
' always call Close when done reading.
myReader.Close()
' always call Close when done with connection.
myConnection.Close()
End Try
End Sub
Your command object is missing the select statement.