Select data from different tables - vb.net - vb.net

I'm trying to select some datas from my database and display it into the textboxes. First is i'm selecting the data from realestate.useraccounts and then to realestate.userprofiles. Its working on the useraccounts but not on the userprofiles.
`
Try
con.Open()
Dim q1 As String
q1 = "select userid,email from realestate.useraccounts where username='" & frmLogin.txtUsername.Text & "'"
cmd = New MySqlCommand(q1, con)
cmd.ExecuteNonQuery()
dr = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
lblUserid.Text = dr("userid")
txtEmail.Text = dr("email")
End If
con.Close()
con.Open()
Dim q2 As String
q2 = "select * from realestate.userprofiles where userid = '" & lblUserid.Text & "'"
cmd = New MySqlCommand(q2, con)
cmd.ExecuteNonQuery()
If dr.HasRows Then
dr.Read()
txtFirst.Text = dr("lastname")
txtLast.Text = dr("firstname")
txtAddress.Text = dr("address")
End If
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try`

You forgot dr = cmd.ExecuteReader() in the second one, so your dr.Read cant read on your second query.
You may also close your reader after use use it.
Let's try this:
Try
con.Open()
Dim q1 As String
q1 = "select userid,email from realestate.useraccounts where username='" & frmLogin.txtUsername.Text & "'"
cmd = New MySqlCommand(q1, con)
cmd.ExecuteNonQuery()
dr = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
lblUserid.Text = dr("userid")
txtEmail.Text = dr("email")
End If
dr.Close()
con.Close()
con.Open()
Dim q2 As String
q2 = "select * from realestate.userprofiles where userid = '" & lblUserid.Text & "'"
cmd = New MySqlCommand(q2, con)
cmd.ExecuteNonQuery()
dr = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
txtFirst.Text = dr("lastname")
txtLast.Text = dr("firstname")
txtAddress.Text = dr("address")
End If
dr.Close()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try`

Related

VB.NET:Updating record in Ms Access

I am creating an employee timing sheet in which they have to insert their timings through pressing timein and timeout buttons. For timein I am creating a new record in database, for that person, and for timeout I am using UPDATING command to update that existing record. Here is my code:
Dim cb As New OleDb.OleDbCommandBuilder(ssda)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim str As String
str = "UPDATE emp_timing SET emp_timing.emp_timeout = '" & OnlyTime & "' WHERE (((emp_timing.emp_code)='" & TextBox1.Text & "') AND ((emp_timing.day)=" & Now.ToString("MM/dd/yyyy") & "))"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
MsgBox("Data added")
TextBox1.Clear()
TextBox2.Clear()
TextBox1.Focus()
ComboBox1.SelectedIndex = -1
Catch ex As Exception
MsgBox(ex.Message)
End Try
My code is working fine but the problem is that it is not updating records in database.
Datatype for fields in Access:
emp_code = Number, emp_timeout = Text, day = Date/Time.
As usual this is caused by your code not using the Parameters collection to pass values to the database engine. This is not really understood until you hit a conversion problem as always happens with dates
str = "UPDATE emp_timing SET emp_timeout = #p1 " & _
"WHERE emp_code = #p2 AND day = #p3"
Using con = new OleDbConnection( dbProvider & dbSource)
Using cmd = New OleDbCommand(str, con)
con.Open()
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = OnlyTime
cmd.Parameters.Add("#p2", OleDbType.Integer).Value = Convert.ToInt32(TextBox1.Text)
cmd.Parameters.Add("#p3", OleDbType.Date).Value = new DateTime(Now.Year, Now.Month, Now.Day)
Try
Dim rowsAdded = cmd.ExecuteNonQuery()
if rowsAdded > 0 Then
MsgBox("Data added")
TextBox1.Clear()
TextBox2.Clear()
TextBox1.Focus()
ComboBox1.SelectedIndex = -1
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using

Storing fetched value in a session

I'm unable to store the value in my session variable.
The fetching from query is done alright as it displays the correct value.
Response.Write(Session("idsess")) Won't return anything.
This is my code:
IS IT A SYNTAX THING?
con.Open()
cmd = New OleDbCommand("SELECT ([password]) FROM userinfo WHERE ([uname]= '" & uname_log.Value & "')", con)
dr = cmd.ExecuteReader
If (dr.Read) Then
If (dr(0).ToString = pass_log.Value) Then
cmd = New OleDbCommand("SELECT [profile_id] FROM userinfo WHERE ([uname]= '" & uname_log.Value & "')", con)
dr = cmd.ExecuteReader
dr.Read()
Response.Write(dr(0).ToString)
If (dr.Read) Then
Session("idsess") = dr.Read()
Response.Write(Session("idsess"))
End If
Else
Response.Write("Wrong Authentification.")
End If
Else
Response.Write("Sign up instead?")
End If
con.Close()
You are not using DataReader correctly; change your code in:
If dr.Read Then
Session("idsess") = dr("profile_id")
Response.Write(Session("idsess"))
End If

error 'There is already an open DataReader associated with this Command which must be closed first.'

I use below code but it gives error on sentence icount = cmd.ExecuteNonQuery
cn.Open()
str = "SELECT [srno],[caste]FROM [SchoolERP].[dbo].[caste] where (caste ='" + (TextBox1.Text) + "')"
cmd = New SqlCommand(str, cn)
dr1 = cmd.ExecuteReader()
If Not dr1.HasRows Then
str = "INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES('" + TextBox1.Text + "')"
cmd = New SqlCommand(str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
Else
MsgBox("Record Exists")
cn.Dispose()
End If
cn.Close()
Try always calling the Close method when you have finished using the DataReader object.
dr1.Close();
Another optionis to turn on MARS , in your connection string just add "MultipleActiveResultSets=True;"
Try this:
Try
insert data in combobox
cmd.Connection = con
cmd.CommandText = "select name from party"
dr = cmd.ExecuteReader()
cb_ms.Items.Add("---Select---")
cb_ms.SelectedIndex = 0
While dr.Read() 'get error here.'
cb_ms.Items.Add(dr("name"))
End While
dr.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
You could just close the datareader before the 2nd query, but it's better still to get this all into a single query in the first place. Moreover, you really need to close that awful sql injection issue.
Try this to fix both issues:
Dim sql As String = _
"IF NOT EXISTS
(
SELECT 1 FROM [SchoolERP].[dbo].[caste] where (caste = #caste )
)
BEGIN
INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES( #caste)
END"
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
'Use actual columnn type from the database here
cmd.Parameters.Add("#caste", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cn.Open()
icount = cmd.ExecuteNonQuery()
MessageBox.Show(icount)
End Using
Use Try.. Catch.. Finally... End Try somehing like this:
Try
cn.Open()
str = "SELECT [srno],[caste]FROM [SchoolERP].[dbo].[caste] where (caste ='" + (TextBox1.Text) + "')"
cmd = New SqlCommand(str, cn)
dr1 = cmd.ExecuteReader()
If Not dr1.HasRows Then
str = "INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES('" + TextBox1.Text + "')"
cmd = New SqlCommand(str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
Else
MsgBox("Record Exists")
cn.Dispose()
End If
cn.Close()
Catch error As Exception
........
Finally
dr1.Close
End Try
I got Answer ... i only close connection before icount = cmd.ExecuteNonQuery this sentence and again open connection...and its works..
thanks disha..

specified cast is not available

can someone help me in this code please
is says specified cast is not available
MysqlConn = New SqlConnection
MysqlConn.ConnectionString =
"Data Source=SABAHALI-SHEIKH;Initial Catalog=md_1103763;Integrated Security=True"
Dim READER As SqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "SELECT [firstname] FROM md_1103763.dbo.customer where firstname='" & ComboBox1.Text & "'"
COMMAND = New SqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
TextBox1.Text = READER.GetInt32("customerID")
TextBox2.Text = READER.GetString("firstname")
TextBox3.Text = READER.GetString("surname")
TextBox4.Text = READER.GetString("contactnumber")
TextBox5.Text = READER.GetString("emailaddress")
End While
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
MysqlConn = New SqlConnection
MysqlConn.ConnectionString =
"Data Source=SABAHALI-SHEIKH;Initial Catalog=md_1103763;Integrated Security=True"
Dim READER As SqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "SELECT [customerID], [firstname], [surname], [contactnumber], [emailaddress] FROM md_1103763.dbo.customer where firstname='" & ComboBox1.Text & "'"
COMMAND = New SqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
TextBox1.Text = READER.GetInt32(READER.GetOrdinal("customerID"))
TextBox2.Text = READER.GetString(READER.GetOrdinal("firstname"))
TextBox3.Text = READER.GetString(READER.GetOrdinal("surname"))
TextBox4.Text = READER.GetString(READER.GetOrdinal("contactnumber"))
TextBox5.Text = READER.GetString(READER.GetOrdinal("emailaddress"))
End While
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
you Must Select all columns in table
and
Try
MysqlConn.Open()
Dim Query As String = Nothing
Query = "SELECT * FROM md_1103763.dbo.customer where firstname='" + ComboBox1.Text & "'"
COMMAND() = New SqlCommand(Query, MysqlConn)
READER = COMMAND().ExecuteReader
While READER.Read
TextBox1.Text = READER("customerID").ToString()
TextBox2.Text = READER("firstname").ToString()
TextBox3.Text = READER("surname").ToString()
TextBox4.Text = READER("contactnumber").ToString()
TextBox5.Text = READER("emailaddress").ToString()
End While
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try

I Cannot Update my database

Whats wrong with these?
My module is:
Imports System.Data.OleDb
Module Module1
Public con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\CITeval\system7\system7\evaluation.mdb")
Public da As OleDbDataAdapter
Public dr As OleDbDataReader
Public cmd As OleDbCommand
Public ds = New DataSet
Public CurrentRow As Integer
Public sql As String
End Module
btn update
Try
Dim Str As String
Str = "update studentsrecord set IDNumber="
Str += """" & txtIDNumber.Text & """"
Str += " where IDNumber="
Str += txtIDNumber.Text.Trim()
con.Open()
cmd = New OleDbCommand(Str, con)
cmd.ExecuteNonQuery()
con.Close()
con.Open()
Str = "update studentsrecord set FirstName="
Str += """" & txtfirst.Text & """"
Str += " where IDNumber="
Str += txtIDNumber.Text.Trim()
con.Open()
cmd = New OleDbCommand(Str, con)
cmd.ExecuteNonQuery()
con.Close()
con.Open()
Str = "update studentsrecord set LastName="
Str += """" & txtlast.Text & """"
Str += " where IDNumber="
Str += txtfirst.Text.Trim()
cmd = New OleDbCommand(Str, con)
cmd.ExecuteNonQuery()
con.Close()
con.Open()
Str = "UPDATE studentsrecord set Course="
Str += """" & cbocourse.Text & """"
Str += " where IDNumber="
Str += txtIDNumber.Text.Trim()
cmd = New OleDbCommand(Str, con)
cmd.ExecuteNonQuery()
con.Close()
con.Open()
Str = "update studentsrecord set Password="
Str += """" & txtpassword.Text & """"
Str += " where IDNumber="
Str += txtIDNumber.Text.Trim()
cmd = New OleDbCommand(Str, con)
cmd.ExecuteNonQuery()
con.Close()
ds.Clear()
da = New OleDbDataAdapter("SELECT * FROM studentsrecord ORDER BY ID", con)
da.Fill(ds, "evaluation")
MsgBox("Updated Successfully...")
Catch ex As Exception
MsgBox(ex.Message & "," & ex.Source)
Finally
If con.State = ConnectionState.Open Then con.Close()
End Try
You don't have to issue a separate UPDATE statement for each field, you can update multiple fields in a single UPDATE statement. Also a better choice is to use parametrized query instead of concatenating strings.
Try this inside of your TRY/CATCH block:
Dim Str As String
Str = "update studentsrecord set FirstName = #FirstName, LastName = #LastName, Course = #Course, Password = #Password where IDNumber = #IDNumber "
cmd = New OleDbCommand(Str, con)
cmd.Parameters.AddWithValue("#FirstName", txtfirst.Text)
cmd.Parameters.AddWithValue("#LastName", txtlast.Text)
cmd.Parameters.AddWithValue("#Course", cbocourse.Text)
cmd.Parameters.AddWithValue("#Password", txtpassword.Text)
cmd.Parameters.AddWithValue("#IDNumber", txtIDNumber.Text.Trim())
con.Open()
cmd.ExecuteNonQuery()
ds.Clear()
da = New OleDbDataAdapter("SELECT * FROM studentsrecord ORDER BY ID", con)
da.Fill(ds, "evaluation")
MsgBox("Updated Successfully...")