Visual Studio Local Database, check if boolean is true - database

first time poster here.. I've been struggeling with this problem for a while.
This piece of code checks if the combination of username and password exist, and if it does it redirects to a new form.
The problem is that i also wanna check if a bit value is true or false, and if it then redirect to another page aswell. I just dont know how to.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim connection As New SqlClient.SqlConnection
Dim command As New SqlClient.SqlCommand
Dim myData As SqlClient.SqlDataReader
Dim Dataset As New DataSet
Dim adaptor As New SqlClient.SqlDataAdapter
connection.ConnectionString = ("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\NewFolder1\Members.mdf;Integrated Security=True")
command.CommandText = "SELECT * FROM [User] WHERE username = '" & TextBox1.Text & "' AND password= '" & TextBox2.Text & "';"
connection.Open()
command.Connection = connection
adaptor.SelectCommand = command
adaptor.Fill(Dataset, 0)
myData = command.ExecuteReader
If Not myData.HasRows Then
TextBox1.Clear()
TextBox2.Clear()
MsgBox("Forkert login, prøv igen")
ElseIf myData.HasRows Then
Me.Hide()
LoggetInd.Show()
End If

Here is what you can do:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connection As New SqlClient.SqlConnection
Dim command As New SqlClient.SqlCommand
Dim myData As SqlClient.SqlDataReader
connection.ConnectionString = ("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\NewFolder1\Members.mdf;Integrated Security=True")
'Don't use SELECT *, call out the columns you want by name, in the order you want them
command.CommandText = "SELECT Username, Password, Bit1 FROM [User] WHERE username = '" & TextBox1.Text & "' AND password= '" & TextBox2.Text & "';"
connection.Open()
command.Connection = connection
myData = command.ExecuteReader(CommandBehavior.CloseConnection)
Dim dbUsername As String, dbPassword As String, dbBit1 As Boolean
If myData.Read Then
'Access the data in the datareader using a 0-based index
'Be careful as this requires you to know the datatype in the database
'If you have a 64bit integer stored in the database,
'you can't call GetInt32, you have to call GetInt64.
dbUsername = myData.GetString(0)
dbPassword = myData.GetString(1)
dbBit1 = myData.GetBoolean(2)
End If
'Don't forget to Close all your DataReaders
myData.Close()
If dbUsername = "" Then
TextBox1.Clear()
TextBox2.Clear()
MsgBox("Forkert login, prøv igen")
Else
If dbBit1 Then
'Redirect as needed
Else
Me.Hide()
LoggetInd.Show()
End If
End If
End Sub
Plutonix is right, you need to use a hash to encrypt/store your passwords. You also need to use SQL parameters. Your current method is an SQL injection playground, among other things.
Call Close on all your datareaders when you are done with them, if not you will have open SQL connections all over the place. When you call ExecuteReader, be sure to use CommandBehavior.CloseConnection. This closes the Connection automatically after you Close the datareader.
This will hopefully get your code working, but you do need to make additional changes for security and stability.
-E

Related

System.InvalidOperationException: 'The ConnectionString property has not been initialized.' microsoft visual studio 2022 with database access

please help me. i have new problem with my code in visual studio 2022.
Imports System.Data.OleDb
Public Class LoginForm1
' TODO: Insert code to perform custom authentication using the provided username and password
' (See http://go.microsoft.com/fwlink/?LinkId=35339).
' The custom principal can then be attached to the current thread's principal as follows:
' My.User.CurrentPrincipal = CustomPrincipal
' where CustomPrincipal is the IPrincipal implementation used to perform authentication.
' Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
' such as the username, display name, etc.
Dim sql As String
Dim con As New OleDb.OleDbConnection
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
sql = "SELECT * FROM tbluseraccounts WHERE userusername = '" & UsernameTextBox.Text & "' and userpassword = '" & PasswordTextBox.Text & "' "
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim dt As New DataTable
con.Open()
With cmd
.Connection = Con
.CommandText = sql
End With
da.SelectCommand = cmd
da.Fill(dt)
If dt.Rows.Count > 0 Then
Me.Hide()
Stock_Master.Show()
Stock_Master.Focus()
UsernameTextBox.Clear()
PasswordTextBox.Clear()
End If
Con.Close()
End Sub
and with error
System.InvalidOperationException: 'The ConnectionString property has
not been initialized.'
The error message is pretty clear. Specify the connection parameters before opening the connection:
Dim con As New OleDb.OleDbConnection
' <snip> .. empty con.
con.Open()

Selecting a specific table from a database from a text box

I am trying to allow the user to select which table they want to take their data from, the UserID text box(UserIDtb) is where the user inputs the table they want. I've tried several different ways of doing it but cant seem to allow the user to select a specific table. This is the code I have so far:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConfirmIDButt.Click
Chart1.Series.Add("Score")
Dim Conn As OleDbConnection = New OleDbConnection
Dim provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Dim dataFile = "\users.accdb" ' Change it to your Access Database location
Conn.ConnectionString = provider & dataFile
Conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [Month], [Score] FROM [Table]", Conn)
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
Chart1.Series("Score").Points.AddXY(dr("Month").ToString, dr("Score").ToString)
End While
dr.Close()
cmd.Dispose()
End Sub

How do i read data from a local SQL database in visual basic? The database was made in Visual Studio

I am having a few issues regarding reading data from a local sql server in visual basic. I have made the database and connected it as a data source but for some reason my data source connection and initial catalog must be incorrect. This is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
con.ConnectionString = ("Data Source = localhost; Initial Catalog=Database1Dataset; Integrated security=true ")
cmd.Connection = con
con.Open()
cmd.CommandText = "select login, password from Table where login = '" & tboxUname.Text & "' and password = '" & tboxPword.Text & "' "
rd = cmd.ExecuteReader
If rd.HasRows Then
frmProperties.Show()
Else
MsgBox("Incorrect Login") 'Else, display a message saying "incorrect login".
Tries += 1
If Tries = 3 Then
MsgBox("Closing Program")
Close()
End If
End If
End Sub
My database is called Database1 and the table is called Table. Thanks for any help.

Displaying Data from SQL to vb.net textbox

I'm trying to retrieve data from sql server to vb.net textbox but i don't know what else to do all the tutorials i have are just to retrieve records from the database to datagrid view..please help..
Private Sub txtrfid_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtrfid.KeyPress
cn.Open()
With cmd
.Connection = cn
.CommandText = "SELECT * FROM Students WHERE RFID like '%" & txtrfid.Text & "%'"
End With
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
cn.Close()
txtname.Text = 'Firstname'
You're populating a DataTable with the data from the database so you then have to get the data from that DataTable into the TextBox. You can do that with data binding, which is how you've probably seen it done with a grid, e.g.
txtname.DataBindings.Add("Text", dt, "Firstname")
That's definitely how you'd do it if you were retrieving multiple records that you wanted to be able to navigate, although you'd probably use a BindingSource in between. If there's only one record then you might instead just move the data manually, e.g.
txtname.Text = CStr(dt.Rows(0)("Firstname"))
If you want to display only a single value (FirstName) from Table then see following piece of code
Using conn As New SqlConnection("connstr")
conn.Open()
Dim cmd As New SqlCommand("", conn)
Dim txtName As String
cmd.CommandText = "SELECT firstname FROM Students WHERE RFID ='" & txtrfid.Text & "'"
txtName = IIf(IsDBNull(cmd.ExecuteScalar), "", cmd.ExecuteScalar)
If txtName <> "" Then
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
Textbox1.Text = ""
Textbox1.Text = txtName
else
MsgBox("No Record Found!", MsgBoxStyle.Information, "INFO.")
End If
End Using
There are many ways to retrieve the data. You can simply retrieve the data from sql database to textbox using sql data reader which is one of my favourite. Let me share to you.
Note : Don't forget to import system.data.sqlclient
Private Sub txtrfid_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtrfid.KeyPress
strConn = "Data Source=" & servernamehere & ";Initial Catalog=" & databasenamehere & ";User ID=" & userid & ";Password=" & password
sqlConn = New SqlConnection(strConn)
sqlConn.Open()
Dim sqlcmd As New SqlCommand("Your query here", sqlConn)
Dim myreader As SqlDataReader
myreader = sqlcmd.ExecuteReader()
myreader.Read()
If myreader.HasRows Then
txtrfid.Text = myreader.Item("column name from sql database table").Tostring
End If
sqlConn.Close()
End Sub
You may catch the exception with Try-Catch Technique.

How to insert textbox values to sql server 2012 database using vb.net

i have a problem with my connection to database dont know where the exact problem is.i have to insert values of textbox to the sql server database.
here is my code:
Imports System.Data
Imports System.Data.SqlClient
Public Class lbluog
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim dr As SqlDataReader
Dim dr1 As SqlDataReader
Dim ra As Integer
Private Sub btnadddata_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadddata.Click
myconnection = New SqlConnection("server=TAHIR-PC;database=myDataBase")
'you need to provide password for sql server
myconnection.Open()
mycommand = New SqlCommand("insert into tblstudentrecords([fname],[lname],[fathername],[phoneno],[address]) values ('" & txtfname.Text & "','" & txtlname.Text & "','" & txtfathername.Text & "','" & txtphoneno.Text & "','" & txtaddress.Text & "')", myconnection)
mycommand.ExecuteNonQuery()
MessageBox.Show("New Row Inserted" & ra)
myconnection.Close()
End Sub
End Class
kindly anyone help me out advance in thanx
I used your variables names mostly but cleaned up the code a little. First I declared the SqlConnection and SqlCommand with using blocks so that they will be Disposed of properly when they're finished. Second, I altered your SQL command and parameterized it. This will help you avoid SQL injection exploits. I used short form "AddWithValue" because I didn't specifically know the datatypes to declare them as they are in your database (this way should work).
Private Sub btnadddata_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadddata.Click
' Assumes your login account has permissions to the database
Using myconnection As SqlConnection = New SqlConnection("server=TAHIR-PC;database=myDataBase;trusted_connection=yes;")
myconnection.Open()
Using mycommand As SqlCommand = myconnection.CreateCommand
' Setup the SQL command with parameters. Parameters protect from SQL injection exploits (and make your SQL easier to read/manage).
mycommand.CommandText = "insert into tblstudentrecords([fname],[lname],[fathername],[phoneno],[address]) values (#fname, #lname, #farthername, #phoneno, #address)"
mycommand.Parameters.AddWithValue("#fname", txtfname.Text)
mycommand.Parameters.AddWithValue("#lname", txtlname.Text)
mycommand.Parameters.AddWithValue("#fathername", txtfathername.Text)
mycommand.Parameters.AddWithValue("#phoneno", txtphoneno.Text)
mycommand.Parameters.AddWithValue("#address", txtaddress.Text)
Dim rowsAffected As Integer = mycommand.ExecuteNonQuery()
' This would be one always in this case unless the statement failed
MessageBox.Show("Rows inserted: " & rowsAffected)
End Using
myconnection.Close()
End Using
End Sub
If you're having a connection issue you should post the specific Exception text (or any other Exception text you're receiving).

Resources