Conversion type Integer Misunderstanding - vb.net

I am sorry for my bad english. I hope somebody could explain what the error The conversion from type MySqlDataReader to type Integer is invalid means.
I was sure that it was a simple 'Dim a Integer, but It is larger than that, or I am just been stupid.
My btnLogin_Click code:
Dim SQL As New MySQLHook
Dim loginResult As Integer
Dim User As TextBox = Me.Controls.Item("TextGebruikersNaam")
Dim Pass As TextBox = Me.Controls.Item("TextGebruikersPass")
If String.IsNullOrEmpty(User.Text) Or String.IsNullOrEmpty(Pass.Text) Then
MsgBox("Voer een gebruikersnaam en wachtwoord in om verder te gaan.", MsgBoxStyle.Exclamation, "Foutmelding")
User.Focus()
Else
loginResult = SQL.Results("SELECT * FROM tblgebruikers " & "WHERE GebruikersNaam='" & User.Text & "' AND " & "GebruikersPass='" & Pass.Text & "'")
If loginResult = 1 Then
' Login was good, todo: add code here
Else
MsgBox("De gebruikersnaam of wachtwoord is onjuist. Probeer het opnieuw of vraag een nieuw wachtwoord aan.", MsgBoxStyle.Exclamation, "Foutmelding")
User.Text = ""
Pass.Text = ""
User.Focus()
End If
End If
My Results code (SQL.Results is from As New MySQLHook)
Public Function Results(ByVal sql)
Try
Dim conn = Connect()
Dim myAdapter As New MySqlDataAdapter
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sql
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
Return myData
Catch myerror As MySqlException
clsError.logMessage("De server retourneerde de volgende foutmelding: " & myerror.Message)
Return DBNull.Value
End Try
End Function
I olso tried using this function but it gave me the same error message:
Public Function num_results(ByVal sql)
Try
Dim conn = Connect()
Dim myAdapter As New MySqlDataAdapter
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sql
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
Return myData
Catch myerror As MySqlException
clsError.logMessage("De server retourneerde de volgende foutmelding: " & myerror.Message)
Return DBNull.Value
End Try
End Function
Why does this conversion error pop-ups? I was sure that 1 or 0 is self-explaining.

Your problem is that you are creating a data reader and returning that. You need to read the integer from the myData variable before returning it.
So, instead of:
Return myData
You should be able to use:
Return myData.GetInt32(0)
The 0 in that statement identifies the column you want to read, and since you are returning a single column from your SQL query, it is in index 0.
Once you have fixed that, please google 'SQL injection' and 'parameterized SQL queries' before continuing. Having your app open to SQL injection is a serious risk.

Related

I am getting this error "There is no row at position 0." vb.net as the frontend and sql server 2008 as the db

This is my code, I m getting error "There is no row at position 0."
Sub loadservicetype()
Dim str As String = "SELECT servicename FROM tbl_activity WHERE activity= '" & CmbActivity.Text & "' "
Dim dt As New DataTable
Dim sdr As New SqlDataAdapter(str, connection)
sdr.Fill(dt)
TxtServiceType.Text = dt.Rows(0)("servicename").ToString
End Sub
First thing is Always Use SQL Parameter to AVOID SQL injection
Like this
Dim commandText As String = "SELECT servicename FROM tbl_activity WHERE activity=#ID"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(commandText, connection)
command.Parameters.Add("#ID", SqlDbType.Int).Value = ID
Try
connection.Open()
Dim rowsAffected As String = command.ExecuteNonQuery()
Catch ex As Exception
throw
End Try
End Using
MSDN SOURCE
Your DataTable is Doesn't Return any rows which You Are Trying to Access
If dt IsNot Nothing Then
If dt.Row.Count>0 Then
TxtServiceType.Text = dt.Rows(0)("servicename").ToString
End If
End If

Syntax Error! >_<

Guy's Cant seem to find my error in VB.Net ! my codes are all right ! but the function still won't save on the database cause of Syntax error in my Insert into statement ! Please help me ! :D!
This is my Code!:D!
Dim Transaction As OleDb.OleDbTransaction = Nothing
Dim Connection As OleDb.OleDbConnection = Nothing
Try
Connection = New OleDb.OleDbConnection(My.Settings.POS_CanteenConnectionString)
Connection.Open()
Transaction = Connection.BeginTransaction
Dim SQL As String = "Insert into Recipt (ReciptDate,ReciptTotal)Values(:0,:1)"
Dim CMD1 As New OleDb.OleDbCommand
CMD1.Connection = Connection
CMD1.Transaction = Transaction
CMD1.CommandText = SQL
CMD1.Parameters.AddWithValue(":0", Now.Date)
CMD1.Parameters.AddWithValue(":1", TextBox4.Text)
CMD1.ExecuteNonQuery()
CMD1.Dispose()
SQL = "Select Max(ReciptID) As MAXID from Recipt"
Dim CMD2 As New OleDb.OleDbCommand
CMD2.Connection = Connection
CMD2.Transaction = Transaction
CMD2.CommandText = SQL
Dim ReciptID As Long = CMD2.ExecuteScalar()
CMD2.Dispose()
Dim I As Integer
For I = 0 To DGV3.Rows.Count - 1
Dim BarCode As String = DGV3.Rows(I).Cells(0).Value
Dim BuyPrice As Decimal = DGV3.Rows(I).Cells(2).Value
Dim SellPrice As Decimal = DGV3.Rows(I).Cells(3).Value
Dim ItemCount As Integer = DGV3.Rows(I).Cells(4).Value
Dim CMD3 As New OleDb.OleDbCommand
SQL = "Insert to ReciptDetails" & _
"(ReciptID,BarCode,ItemCount,ItemBuyPrice,ItemSellPrice)" & _
"Values" & _
"(:0 ,:1 ,:2 ,:3 ,:4 )"
CMD3.Connection = Connection
CMD3.Transaction = Transaction
CMD3.CommandText = SQL
CMD3.Parameters.AddWithValue(":0", ReciptID)
CMD3.Parameters.AddWithValue(":1", BarCode)
CMD3.Parameters.AddWithValue(":2", BuyPrice)
CMD3.Parameters.AddWithValue(":3", ItemCount)
CMD3.Parameters.AddWithValue(":4", SellPrice)
CMD3.ExecuteNonQuery()
CMD3.Dispose()
Next
Transaction.Commit()
Transaction.Dispose()
Connection.Close()
Connection.Dispose()
DGV3.Rows.Clear()
TextBox4.Text = ""
Catch ex As Exception
If Transaction IsNot Nothing Then
Transaction.Rollback()
End If
If Connection IsNot Nothing Then
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
End If
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "ERROR")
End Try
Firstly, I don't think sp parameters are called by : prefix, you should use # instead. you'll therefore need to replace the .AddWithValue (everywhere) by;
CMD1.Parameters.AddWithValue("#0", Now.Date)
CMD1.Parameters.AddWithValue("#1", TextBox4.Text)
Secondly, I think the Insert syntax isn't right, you've place TO instead of INTO and space missing. Try this;
SQL = "Insert into ReciptDetails " & _
"(ReciptID, BarCode, ItemCount, ItemBuyPrice, ItemSellPrice)" & _
" Values (#0, #1, #2, #3, #4)"

How do I return a list of integers using a VB.NET function?

I am working on a report in SSRS2005 where I need to use some VB.NET code to go out to a different database than the one in the report and return a list of integers (user IDs). I need to use some VB.NET code to do this. I have some code that 'works' in the sense that it does not throw any errors and I get values returned. However, I only get the first value and not the entire list. Here is what I have so far:
Public Function GetUsers(ByVal param As Integer) As String
Dim sqlCon As New System.Data.SqlClient.SqlConnection
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim dRet As String
Dim sCmdText As String
sqlCon.ConnectionString = "data source=myServer;initial catalog=myDatabase;Integrated Security=true"
cmd = New System.Data.SqlClient.SqlCommand
sCmdText = "SELECT UsersRowID FROM dbo.tvf_Get_Users("
'cmd.CommandType = CommandType.Text
cmd.Connection = sqlCon
cmd.CommandTimeout = 0
sCmdText = sCmdText & param
sCmdText = sCmdText & ")"
cmd.CommandText = sCmdText
If sqlCon.State <> System.Data.ConnectionState.Open Then
sqlCon.Open()
End If
dRet = cmd.ExecuteScalar() & ""
sqlCon.Close()
Return dRet
End Function
I have tried experimenting with using the DataSet data type but I get error messages that I cannot cast DataSet as a String.
Any ideas what I need to do to get this to work?
modify your code to the following
Public Function GetUsers(ByVal param As Integer) As String
'
Dim sqlCon As New System.Data.SqlClient.SqlConnection
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim dtAdapter As Data.SqlClient.SqlDataReader
Dim dRet As String
Dim sCmdText As String
'
'connection
sqlCon.ConnectionString = "data source=myServer;initial catalog=myDatabase;Integrated Security=true"
sqlCon.Open()
'
'query
sCmdText = "SELECT UsersRowID FROM dbo.tvf_Get_Users(" & param & ")"
'
'command
cmd = New System.Data.SqlClient.SqlCommand(sCmdText, sqlCon)
cmd.CommandTimeout = 0
'
'main course
If cmd.Connection.State = Data.ConnectionState.Closed Then cmd.Connection.Open()
dtAdapter = cmd.ExecuteReader(Data.CommandBehavior.CloseConnection)
If dtAdapter.HasRows Then
While dtAdapter.Read()
' following assumes "dbUserId" is the userid field in the database
' also use pipe "|" to split the userid's whens theres more than one
' this is so you can still use STRING as the function return and not an ARRAY
dRet = dRet & dtAdapter.GetValue(dtAdapter.GetOrdinal("dbUserId")) & "|"
End While
End If
If cmd.Connection.State <> Data.ConnectionState.Closed Then cmd.Connection.Close()
Return dRet
'
End Function

How do I catch an SQL exception in a VB.NET 2010 code?

Okay, I am building a VB.NET system but I'm having troubles in catching an SQL exception in some parts of my code. In short, I am using a SELECT sql query to retrieve a particular record and I want to determine whether a record exist in a MSAccess database so that I don't retrieve 0 rows. 0 rows will lead to an exception during printing to a TextField. The following is a sample code I'm working on:
If txSearch.Text = "" Then
MsgBox("Please type the user id or use the barcode reader to scan", MsgBoxStyle.OkOnly, "Search Field Empty")
End If
'ElseIf txSearch.Text != "" Then
If txSearch.Text <> "" Then
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim dt As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim de As OleDb.OleDbDataAdapter
Dim sql As String
Dim sql1 As String
Dim temp_num As Integer
Dim cmd As New OleDb.OleDbCommand
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = new.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim search As String
search = txSearch.Text
MessageBox.Show("You are going to search for " + search + ". Click OK to continue.")
sql = "SELECT * FROM Student_Details WHERE Admin_No = '" & txSearch.Text & "'"
sql1 = "SELECT * FROM Laptop_Details WHERE Admin_No = '" & txSearch.Text & "'"
da = New OleDb.OleDbDataAdapter(sql, con)
de = New OleDb.OleDbDataAdapter(sql1, con)
'Dim check As Integer = sql.
'If check > 0 Then
'da.SelectCommand = cmd
ds = New DataSet("Student_Details")
da.Fill(ds, "Student_Details")
dt = New DataSet("Laptop_Details")
de.Fill(dt, "Laptop_Details")
'con.Close()
'If sql <> "" And sql1 <> "" Then
'If ds.Equals(1) And ds.Equals(1) Then
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
Dim com As New OleDb.OleDbCommand(sql, con)
Dim com1 As New OleDb.OleDbCommand(sql1, con)
Try
temp_num = com.ExecuteNonQuery
temp_num = com1.ExecuteNonQuery
Catch ex As IndexOutOfRangeException
Trace.WriteLine(ex.ToString)
End Try
con.Close()
'End If
'End If
End If
Try something like this:
if ds.Tables("Student_Details").Rows.Count > 0
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
End if
if ds.Tables("Laptop_Details").Rows.Count > 0
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
End if
To help you with your comment I would do it like that:
if ds.Tables("Student_Details").Rows.Count > 0 And ds.Tables("Laptop_Details").Rows.Count > 0
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
else
MsgBox("The user with id "+txSearch.Text+" does not exist")
end if
Try to use try-catch statement:
Try
Your code here for your query statements.
Catch ex as Exception MsgBox(ex.Message)End Try

vb login session

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.