vb login session - vb.net

Hi I'm completely lost on this piece of code (also very new) I am trying to create a session after the else statement. How do you create a session and for it to be read by another file ?
Dim conn As MySqlConnection
'connect to DB
conn = New MySqlConnection()
conn.ConnectionString = "server=localhost;Port=3306; user id=****; password=****; database=testtable"
'see if connection failed.
Try
conn.Open()
Catch myerror As MySqlException
MessageBox.Show("Error Connection to Database: " & myerror.Message)
End Try
'sql query
Dim myAdapter As New MySqlDataAdapter
Dim sqlquery = "SELECT * FROM members Where login='" & UsernameTextBox.Text & "' and passwd='" & PasswordTextBox.Text & "'"
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
'start query
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
'see if user exits.
If myData.HasRows = 0 Then
MessageBox.Show("Invalid Username/Password", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Dim login As String = System.Web.HttpContext.Current.Session("login")
System.Web.HttpContext.Current.Session("login") = UsernameTextBox.Text
Dim Form1 = New Form1
Form1.Show()
Me.Visible = False
End If
Thanks for any help

Session only exists in ASP.Net.
You should pass information in constructor parameters and/or properties of your form classes.

Related

Database locked in vb.net when trying to update data in vb.net

Hello I have a simple method to update customer details in one of my database tables however when i try to update it an error occurs saying the database is locked. I have no idea how to fix this because my add and delete queries work just fine.
This is the error message:
System.Data.SQLite.SQLiteException: 'database is locked
database is locked'
Public Sub updateguest(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN UPDATED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Dim usql As String = "UPDATE Customers SET fname = '" & txtFName.Text & "'" & "WHERE CustomerID ='" & txtSearchID.Text & "'"
updateguest(usql)
End Sub
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
Dim msql, msql1 As String
Dim con As New SQLiteConnection(ConnectionString)
con.Open()
msql = "SELECT * FROM Customers Where Fname Like '" & txtSearchName.Text & "%'"
msql1 = "SELECT * FROM Customers Where CustomerID '" & txtSearchID.Text & "'"
Dim cmd As New SQLiteCommand(msql, con)
Dim cmd1 As New SQLiteCommand(msql1, con)
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
Dim mdr As SQLiteDataReader = cmd.ExecuteReader()
If mdr.Read() Then
If txtSearchName.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE fname LIKE'" & txtSearchName.Text & "%'"
Dim con1 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con1)
con1.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con1.Close()
txtSearchID.Clear()
ElseIf txtSearchID.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE CustomerID ='" & txtSearchID.Text & "'"
Dim con2 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con2)
con2.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con2.Close()
txtSearchName.Clear()
End If
Else
MsgBox("No data found")
End If
End Sub
Private Sub IbtnDelete_Click(sender As Object, e As EventArgs) Handles ibtnDelete.Click
Dim dsql As String = "DELETE FROM customers WHERE customerid = " & txtSearchID.Text & ""
deleteme(dsql)
updatedgv(dgvCustomerInfo)
txtSearchID.Clear()
txtSearchName.Clear()
End Sub
Public Sub deleteme(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN DELTED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN DELTED!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
You made a good start on keeping your database code separate from you user interface code. However, any message boxes should be shown in the user interface and any sql statements should be written in the data access code.
I used Using...End Using blocks to ensure that database objects are closed and disposed. I used parameters to protect against sql injection. I am not too sure of the mapping of DbType types to Sqlite types. You might have to fool with that a bit. In you original Update statement you had the ID value in quotes. This would pass a string. When you use parameters, you don't have to worry about that or ampersands and double quotes. Just one clean string.
Private ConStr As String = "Your connection string"
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
End Using
Return Result
End Function
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Saving data to access not working, despite no errors

Hey I'm trying to use this code to save to my access database and although there are no errors and it says data saved, my access database doesn't receive the new data. What's wrong with it?
Private Sub savenew()
Dim conn As New OleDbConnection
conn = New OleDbConnection
dbprovider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbsource = "Data Source = FULL YUGIOH ACCESS DATABASE.accdb;"
conn.ConnectionString = dbprovider & dbsource
Dim reader As OleDbDataReader
Dim command As OleDbCommand
Try
conn.Open()
Dim query As String
query = "insert into item(name) values ('" & TextBox4.Text & "')"
command = New OleDbCommand(query, conn)
reader = command.ExecuteReader
MsgBox("data saved")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
(table in my database is called item, and column is called name.)

Visual Basic 2015 (Visual Studio)

I'm trying to create a Login Form using Visual Basic 2015 in Visual Studio. I've followed the instructions from a video that I've watched, however, an error occurred when I tried to run the code.
Here's the codes I've done so far:
Private Sub picgo1_Click(sender As Object, e As EventArgs) Handles picgo1.Click
openConn()
Dim dr As SqlDataReader
Dim cmd As SqlCommand
Dim sqlsyntax As String
cmd = New SqlCommand
cmd.CommandType = CommandType.Text
cmd.Connection = conn
sqlsyntax = "select * from tblusers where user = '" & txtuser.Text & "' and pass = '" & txtpass.Text & "'"
cmd.CommandText = sqlsyntax
dr = cmd.ExecuteReader()
If dr.HasRows Then
MsgBox("Access Granted! Welcome '" & txtuser.Text & "'")
Else
MsgBox("Access Denied! Incorrect Username or Password!")
End If
conn.Close()
cmd.Dispose()
End Sub
Another for Module
Imports System.Data.SqlClient
Module ModuleConnections
Public conn As SqlConnection
Sub openConn()
Try
conn = New SqlConnection("Data Source=E:\HRIMS\HRIMS V1.0\WINDOWSAPPLICATION2\HRIMSDB.MDF;Integrated security=True")
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Catch ex As Exception
MsgBox("Connecting to Database Failed" & ex.ToString)
End Try
End Sub
End Module
When I tried to run the form, here is the error I'm getting. Then when I pressed ok, it points me to this line.
I'm still trying to learn, so please don't be too hard on me :D
Thank you in advance.
Try:
Public conn As SqlConnection
Public Sub openConn()
conn = New SqlConnection(CONNECTIONSTRING)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Return conn
End Function
Login code:
Using cmd As New SqlCommand("SELECT *
FROM tblusers
WHERE user = #userName
AND pass = #userPass", openConn)
'Parameterize your query to be safe from SQL Injection
cmd.Parameters.AddWithValue("#userName", txtuser.Text)
cmd.Parameters.AddWithValue("#userPass", txtpass.Text)
Using rdr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleResult)
Dim Login As Object = 0
If rdr.HasRows Then
rdr.Read
Login = rdr(Login)
End If
If Login = Nothing Then
MsgBox("Access Denied! Incorrect Username or Password!")
Else
'MsgBox("Access Granted! Welcome '" & txtuser.Text & "'")
MsgBox(String.Format("Access Granted! Welcome {0}!", txtuser.text)
End If
End Using
End Using

Best way to deal with Open Datareader Error (vb.net and mysql)

My Project running on VS 2013 & MySQL, I have declared public variable conn as mysqlconnection and I use the same connection all over the project to perform any database operation.
Public conn As New MySqlConnection
Public Sub createConnection()
If conn.State = ConnectionState.Closed Then
conn.ConnectionString = parseConfigXML()
conn.Open()
End If
End Sub
Public Function parseConfigXML()
Try
Dim m_xmld As XmlDocument
Dim m_nodelist As XmlNodeList
Dim m_node As XmlNode
m_xmld = New XmlDocument()
m_xmld.Load("../../../appconfig.xml")
m_nodelist = m_xmld.SelectNodes("/app/config")
Dim hostname, dbname, dbuser, dbpassword As String
hostname = ""
dbname = ""
dbuser = ""
dbpassword = ""
For Each m_node In m_nodelist
hostname = m_node.ChildNodes.Item(0).InnerText.ToString
dbname = m_node.ChildNodes.Item(1).InnerText.ToString
dbuser = m_node.ChildNodes.Item(2).InnerText.ToString
dbpassword = m_node.ChildNodes.Item(3).InnerText.ToString
Next
Dim connectionString = "Database=" & dbname & "; Data Source=" & hostname & "; User Id=" & dbuser & ";Password=" & dbpassword & "; Character Set=utf8"
Return connectionString
Catch errorVariable As Exception
MsgBox("Oops, An error occured: " & errorVariable.ToString)
End Try
End Function
Whenever connection is required, I use it as follows:
Try
Dim query As String = "select * from tbl_lang where lang_status=1"
Dim cmd As New MySqlCommand(query, conn)
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
If dr.HasRows Then
Do While dr.Read
cmb.Items.Add(dr.GetString("lang_name"))
Loop
End If
cmb.SelectedItem = "English"
If Not dr.IsClosed Then dr.Close()
Catch ex As Exception
lbl_error.text="Oops, An error occured: " & ex.ToString
End Try
I always have this issue when the code is reused: There is already open datareader for this connection.
What is the best way to deal with it? someone had mentioned to use open new connection for every query and then close it. Somehow, I am not convinced with it as it may create performance issues.
Please suggest the best way to overcome the issue.

Parameter with odbc error

i have a problem with supply parameter to store procedure with odbc, this is my procedure in module form Public cmd As OdbcCommand
Private Sub cmdapprove_Click(sender As Object, e As EventArgs) Handles cmdapprove.Click
cmd = New OdbcCommand("select * from mk_cuti where mk_nik='" & txtnik.Text & "'", conn)
rd = cmd.ExecuteReader
rd.Read()
rd.Close()
Call opendb()
If txtstatus.Text = 1 Then
Using (conn)
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sp_update_data_trans_cuti_terbawa"
cmd.Parameters.AddWithValue("#mk_nik", Me.txtnik.Text)
cmd.ExecuteNonQuery()
End Using
Dim updatestatus_hrd As String = "Update input_cuti set status_hrd=1 " & _
"where no_input='" & txtnoinput.Text & "'"
cmd = New OdbcCommand(updatestatus_hrd, conn)
cmd.ExecuteNonQuery()
Call datacutikaryawan()
Else
Dim updatestatus_hrd As String = "Update input_cuti set status_hrd=1 " & _
"where no_input='" & txtnoinput.Text & "'"
cmd = New OdbcCommand(updatestatus_hrd, conn)
cmd.ExecuteNonQuery()
Call datacutikaryawan()
End If
End Sub
when i run this procedure, i got massage this
ERROR [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Procedure
or function 'sp_update_data_trans_cuti_terbawa' expects parameter
'#mk_nik', which was not supplied.
I think anyone can help me? please
Here's one with your class:
Dim conn As New OdbcConnection(sConnString)
conn.Open()
Dim sqlCommand As String = "sp_update_data_trans_cuti_terbawa #mk_nik='" & Me.txtnik.Text & "'"
Dim command As New OdbcCommand(sqlCommand)
command.CommandType = CommandType.StoredProcedure
command.Connection = conn
command.ExecuteNonQuery()
Aight, I'm off to the nearest pub.
conn.execute("sp_update_data_trans_cuti_terbawa #mk_nik='" & Me.txtnik.Text & "'")
I have module with this
Imports System.Data.Odbc
Imports System.Data
Module koneksi
Public conn As OdbcConnection
Public str As String
Public da As OdbcDataAdapter
Public ds As DataSet
Public cmd As OdbcCommand
Public rd As OdbcDataReader
Sub opendb()
str = "Dsn=pmscuti;database=att2000;server=pams-01;uid=sa;pwd=pams123"
conn = New OdbcConnection(str)
If conn.State = ConnectionState.Closed Then
Try
conn.Open()
'MsgBox("Connection Successfully")
Catch ex As Exception
MsgBox(ex.Message)
Application.Exit()
End Try
End If
End Sub
End Module
can i know where the problem?