VB.NET SQL Statement - sql

I am relatively new to programming in VB.
Currently, I have a login page that works fine. After successful login, my user is directed to another form which connects back into an MS Access table and presents data on the screen for them.
I take the logged in user and equal it to a label on the secondary form (after they login). Basically I want to have a SQL select statement for if the Username column in my access db equals that label, then to pull back the data for that unique user. Here is my current code:
lblUsername.Text = login.txtUsername.Text
DbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
DbSource = "Data Source = C:\loginprogram\studentclasslist.mdb"
con.ConnectionString = DbProvider & DbSource
con.Open()
strSQL = "SELECT * FROM Table1 WHERE Username = '" + Label1.Text + "'""
da = New OleDb.OleDbDataAdapter(strSQL, con)
da.Fill(ds, "studentclasslist")
con.Close()
It doesn't work. When I take the where statement out and just do "Select * From Table1" it works fine, but doesn't give me a unique logged in user, which is my goal.
Please help!

You should store your login user id in the session when user logged in successfully.
//In your login page
Session["myUser"] = txtUsername.Text
Then, you can use the user id from Session anywhere in your application.
//In your other page.
Dim Cmd As OleDbCommand = connection.CreateCommand()
Cmd.CommandText = "SELECT * FROM Table1 WHERE Username=?"
Cmd.Parameters.Add("#Username",OleDbType.Text,50).Value = Session["myUser"]
Dim da As New OleDbDataAdapter(Cmd)
Dim dt As New DataTable()
da.Fill(dt)

It din't work because of, misused double quotation.
May be Something like this
lblUsername.Text = login.txtUsername.Text
DbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
DbSource = "Data Source = C:\loginprogram\studentclasslist.mdb"
con.ConnectionString = DbProvider & DbSource
con.Open()
strSQL = "SELECT * FROM Table1 WHERE Username = '" & Label1.Text & "'"
da = New OleDb.OleDbDataAdapter(strSQL, con)
da.Fill(ds, "studentclasslist")
con.Close()
But this will leads you to SQL injection attacks. use parameterized queries to treat input as values in your SQL queries.
lblUsername.Text = login.txtUsername.Text
DbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
DbSource = "Data Source = C:\loginprogram\studentclasslist.mdb"
con.ConnectionString = DbProvider & DbSource
con.Open()
strSQL = "SELECT * FROM Table1 WHERE Username = #UserName"
da = New OleDb.OleDbDataAdapter(strSQL, con)
da.SelectCommand.Parameters.Add("#UserName",SqlDbType.nvarchar,50).Value = Label1.Text
da.Fill(ds, "studentclasslist")
con.Close()

To prevent from SQL injection as parameters as already been widely suggested. Additionally, you could use Using for you connection to dispose right away the connection after it is being used like:
Using con As New OleDbConnection(DbProvider & DbSource)
con.Open()
strSQL = "SELECT * FROM Table1 WHERE Username = #UserName"
da = New OleDb.OleDbDataAdapter(strSQL, con)
da.SelectCommand.Parameters.Add("#UserName",SqlDbType.nvarchar,50).Value = Label1.Text
da.Fill(ds, "studentclasslist")
End Using
Secondly, you can put the data on a DataTable
Dim dt as new DataTable
dt = ds.Tables(0)
And assuming that you have one record match you could check if there are records by checking Records.Count and if there is save it to a DataRow and then Textboxes.
If (dt.Rows.Count > 0) Then
Dim dr as DataRow = dt.Rows(0)
'Field names and Textbox names below are just mine
txtUserName.Text = dr.Item("Username")
txtPassword.Text = dr.Item("Password")
txtUserlevel.Text = dr.Item("UserLevel")
End If
So, all in all it would probably look like this:
lblUsername.Text = login.txtUsername.Text
DbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
DbSource = "Data Source = C:\loginprogram\studentclasslist.mdb"
Using con As New OleDbConnection(DbProvider & DbSource)
Dim dt as new DataTable
con.Open()
strSQL = "SELECT * FROM Table1 WHERE Username = #UserName"
da = New OleDb.OleDbDataAdapter(strSQL, con)
da.SelectCommand.Parameters.Add("#UserName",SqlDbType.nvarchar,50).Value = Label1.Text
da.Fill(ds, "studentclasslist")
dt = ds.Tables(0)
If (dt.Rows.Count > 0) Then
Dim dr as DataRow = dt.Rows(0)
'Field names and Textbox names below are just mine
txtUserName.Text = dr.Item("Username")
txtPassword.Text = dr.Item("Password")
txtUserlevel.Text = dr.Item("UserLevel")
End If
End Using

thanks everyone. it was the double quote. works now but next is making it sql injection proof which i will learn how to use parameterized queries to prevent against.

Related

Log-In module with SQL Server not working

I have created two form for Login module. One for the admins and one for the customers.
Admin:
Dim con As SqlConnection = New SqlConnection("Data Source=LEGIONPC;Initial Catalog=master;Integrated Security=True")
Dim cmd As SqlCommand = New SqlCommand("select * from tbAdmin where admin_id=' " + txtUsername.Text + " ' and admin_password='" + txtPassword.Text + "'", con)
Dim sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
If (dt.Rows.Count > 0) Then
MessageBox.Show("Correct.", "Log-In")
Else
MessageBox.Show("Invalid.", "Log-In")
End If
Customer:
Dim con As SqlConnection = New SqlConnection("Data Source=LEGIONPC;Initial Catalog=master;Integrated Security=True")
Dim cmd As SqlCommand = New SqlCommand("select * from tbLogin where username=' " + txtUsername.Text + " ' and pass='" + txtPassword.Text + "'", con)
Dim sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
If (dt.Rows.Count > 0) Then
MessageBox.Show("Correct.", "Log-In")
Else
MessageBox.Show("Invalid.", "Log-In")
End If
They are basically just the same, except that both of them are in different form and are based on different tables. But for some reason, the Customer log in is not working, even though the inputs are correct and matches the records in database, it always shows it's invalid.
In database, tbAdmin's primary key is admin_id and tbCustomer's primary key is username.
Is it possible that it's kind of interrupting the connection because they basically all have the same variable name? But they're in different form and admin log in is perfectly fine.
I would like to apologize, I am new to connecting vb.net to sql.
one thing I notice is you leave a space between the colon
Try this
"select * from tbLogin where username='" & txtUsername.Text & "' and pass='" & txtPassword.Text & "'"
Also if you do not want it to be case sensitive you always use 'like'
"select * from tbLogin where username like '" & txtUsername.Text & "' and pass like '" & txtPassword.Text & "'"

Working out how many records are in a database or dataset in vb

I am currently working on a project where I need to know how many records are in a single table in a database as the number of records changes dependent on inputs made by the user. Is there any way to program a function that will work out the number of records is my database?
Here is the code I have at current which isn't working.
dbProvider = "PROVIDER=Microsoft.JET.OLEDB.4.0;"
TheDatabase = "/TeachersData.mdb"
FullDatabasePath = CurDir() & TheDatabase
dbSource = "Data Source = " & FullDatabasePath
con.ConnectionString = dbProvider & dbSource
con.Open()
NoOfRecords = "SELECT COUNT(*) FROM Teachers"
sql = "SELECT * FROM Teachers"
RecordNumbers = New OleDbDataAdapter(NoOfRecords, con)
da = New OleDbDataAdapter(Sql, con)
da.Fill(ds, "TeachersData")
con.Close()
End Sub
Sub VerifyDetails()
For i = 0 To Len(RecordNumbers)
If Initials.Text = ds.Tables("TeachersData").Rows(i).Item(1) Then
Salt = ds.Tables("TeachersData").Rows(i).Item(3)
End If
Next
You are making some confusion with two OleDbDataAdapters. You prepare one with the correct query (RecordNumbers) but then you fill another one (da).
But you really don't need any OleDbDataAdapter for this. Just an OleDbCommand to execute
con.Open()
Dim cmd = new OleDbCommand("SELECT COUNT(*) FROM Teachers", con)
Dim count = Convert.ToInt32(cmd.ExecuteScalar())
Now count contains the number of records present in the Teachers table.

Datagridview WHERE SQL Error

I'm trying to automatically fill a datagridview upon loading. This is what I have so far
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Administratot\Downloads\RailwayDatabase2.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from tbl_shifts WHERE EmployeeName = '" & EmployeeLogin.usersname & "' AND Completed = True", MyConn)
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView2.DataSource = view
When I attempt this, I am met with an error reading
Cannot find table 0.
You must fill the dataset first.
da = New OleDbDataAdapter("Select * from tbl_shifts WHERE EmployeeName = '" & EmployeeLogin.usersname & "' AND Completed = True", MyConn)
da.Fill(ds)
Dim view As New DataView(tables(0))
This might help. Keep it simple.
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Administratot\Downloads\RailwayDatabase2.accdb"
Dim MyConn As New OleDbConnection(connString)
Dim da As OleDbDataAdapter
Dim ds As DataSet
--For error handling, do this
Try
'Open the connection
MyConn.Open()
'Fill the dataset
da = New OleDbDataAdapter("Select * from tbl_shifts WHERE EmployeeName = '" & EmployeeLogin.usersname & "' AND Completed = True", MyConn)
ds = New DataSet
da.Fill(ds)
'Fill datagridview
DataGridView2.DataSource = ds.Tables(0)
'Close the connection
MyConn.Close()
Catch ex As Exception
'Make sure connection is closed
If MyConn.State <> ConnectionState.Closed Then MyConn.Close()
End Try
And of course, you will put second group of code in Form_Load Event.

How to update multiple data to Database?

Does anyone knows how to fix this code to and make it work properly?. I want to update my DB that will get the value in Combo box. Is it possible to update 1 or more value at the same time in DB?
CODE
cmd.CommandText = "UPDATE tblStudent SET (course = '" & ComboBox2.Text & "',section = '" & ComboBox5.Text & "') WHERE yearLevel = '" & yearLevel.Text & "';"
Thanks in advance!!
First, you should use sql-parameters instead of string concatenation to prevent possible sql-injection.
Also, your code already updates multiple records if there are more than one with the same yearLevel.
Dim sql = "UPDATE tblStudent SET course = #course,section = #section WHERE yearLevel = #yearLevel"
Using cmd = New SqlCommand(sql, con)
Dim p1 As New SqlParameter("#course", SqlDbType.VarChar)
p1.Value = ComboBox2.Text
cmd.Parameters.Add(p1)
Dim p2 As New SqlParameter("#course", SqlDbType.VarChar)
p2.Value = ComboBox5.Text
cmd.Parameters.Add(p2)
Dim p3 As New SqlParameter("#course", SqlDbType.Int)
p3.Value = Int32.Parse(yearLevel.Text)
cmd.Parameters.Add(p3)
Dim updatedCount = cmd.ExecuteNonQuery()
End Using
Note that i didn't know the data -type of your columns, so modify it accordingly. I just wanted to show you that it's important to use the correct type in the first place.
This is is for 'INSERTING', however, it can be adapted for 'UPDATING' quite easily:
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=atisource;Initial Catalog=BillingSys;Persist Security Info=True;User ID=sa;Password=12345678"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO table([field1], [field2]) VALUES([Value1], [Value2])"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
source: can be found here
where you have declared field1, and assigned it Combobox2.SelectedValue etc

VB.NET error adding a record to database

I'm using the code from http://homeandlearn.co.uk/NET/nets12p9.html for adding a record to the database.
It says when using a commandbuilder I should not get the error message:
Update requires a valid InsertCommand when passed DataRow collection with new rows.
However when I do the update I still get the error message. How can I fix this?
This is my code:
Dim dbProv As String
Dim dbSource As String
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As New OleDb.OleDbDataAdapter
Dim sql As String
Dim Command As OleDb.OleDbCommand
Dim dr As DataRow
Dim cb As New OleDb.OleDbCommandBuilder(da)
sql = "SELECT * FROM Cliënten"
dbProv = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = [mydatabase]"
con.ConnectionString = dbProv & dbSource
con.Open()
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Cliënten")
dr = ds.Tables("Cliënten").NewRow()
dr.Item("Field1") = TextBox1.Text
dr.Item("Field2") = TextBox2.Text
ds.Tables("Cliënten").Rows.Add(dr)
da.Update(ds, "Cliënten")
MsgBox("New Record added to the Database")
con.Close()
To make da.Update() works, you must assign a valid InsertCommand, then the DataAdapter will execute it automatically. Here an example:
da.InsertCommand = New OleDb.OleDbCommand("INTERT INTO Cliënten (Field1, Field2) VALUES (#field1, #field2)")
da.InsertCommand.Parameters.Add(New OleDb.OleDbParameter("#field1", OleDb.OleDbType.VarChar, 0, "Field1"))
da.InsertCommand.Parameters.Add(New OleDb.OleDbParameter("#field2", OleDb.OleDbType.VarChar, 0, "Field2"))
da.Update(ds, "Cliënten")
WARNING: I've presumed you are using OleDb.OleDbType.VarChar for Field1 and Field2; if not you have to replace it with correct DB data format.
From what I read here it seems as though CommandBuilder should auto-generate the INSERT command for you based on the SELECT.
I think you are creating your CommandBuilder object too early - ie Before you specify the SELECT command / initialise Connection etc.
Perhaps this may work better...
Dim dbProv As String
Dim dbSource As String
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As New OleDb.OleDbDataAdapter
Dim sql As String
Dim Command As OleDb.OleDbCommand
Dim dr As DataRow
sql = "SELECT * FROM Cliënten" 'Consider specifying columns
'individually rather than using *
dbProv = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = [mydatabase]"
con.ConnectionString = dbProv & dbSource
con.Open()
da = New OleDb.OleDbDataAdapter(sql, con)
Dim cb As New OleDb.OleDbCommandBuilder(da) 'Init CommandBuilder here
cb.RefreshSchema() 'This may also help
da.Fill(ds, "Cliënten")
dr = ds.Tables("Cliënten").NewRow()
dr.Item("Field1") = TextBox1.Text
dr.Item("Field2") = TextBox2.Text
ds.Tables("Cliënten").Rows.Add(dr)
da.Update(ds, "Cliënten")
MsgBox("New Record added to the Database")
con.Close()