I have this code:
comkonsultasi = New OleDbCommand("select count(idkonsultasi) from dkonsultasi where idgejala='" & idgejala & "'", conn)
drkonsultasi = comkonsultasi.ExecuteReader
jgejala = drkonsultasi.Item(0)
When it runs, I get this exception message on the last line:
InvalidOperationException was unhandled. No data exists for the row/column.
Can anyone can help to resolve this problem?
You have to Read() from the DataReader. It's also very bad to use string concatenation to put data into an SQL query like that. You must use query parameters instead:
Dim sql As String = "select count(idkonsultasi) from dkonsultasi where idgejala= ?"
Using conn As New OleDbConnection("connection string here"), _
comkonsultasi As New OleDbCommand(sql, conn)
'Use the actual type and length from the database for this line
comkonsultasi.Parameters.Add("idgejala", OleDbType.VarWChar, 50).Value = idgejala
conn.Open()
Using drkonsultasi As OleDbDataReader = comkonsultasi.ExecuteReader()
If drkonsultasi.Read() Then
jgejala = drkonsultasi.Item(0)
End Using
End Using
End Using
Related
I am trying to convert VBA code into VB.net and I have made it to a point but I can't convert resultset into vb.net. RS was 'dim as resultset' in VBA, thought i could just change it to dataset but am getting errors with the '.fields' and other options?
Function GetG(sDB As String, sServ As String, sJob As String) As String
'sDB = Database name, sServ = Server\Instance, path = job.path
Dim conString As String = ("driver={SQL Server};server = " &
TextBox1.Text & " ; uid = username;pwd=password:database = " &
TextBox2.Text)
Dim RS As DataSet
Dim conn As SqlConnection = New SqlConnection(conString)
Dim cmd As SqlCommand
conn.Open()
'This is where my problems are occuring
cmd = New SqlCommand("SELECT [ID],[Name] FROM dbo.PropertyTypes")
Do While Not RS.Tables(0).Rows.Count = 0
If RS.Fields(1).Value = sJob Then
GetG = RS.Fields(0).Value
GetG = Mid(GetG, 2, 36)
Exit Do
End If
DataSet.MoveNext
Loop
conn.Close
End Function
Based on my understanding and some guesswork, here is what I came up with for what I think you're wanting.
As I stated in my comment above, it appears you can just use a WHERE clause to get the exact record you want (assuming a single instance of sJob appears in the name column).
Build the connectionstring off the input arguments, not controls on your form. That is after all why you allow for arguments to be passed along. Also note that there is a SqlCommandBuilder object that may be of interest. But for now
Function GetG(sDB As String, sServ As String, sJob As String) As String
'we'll pretend your connectionstring is correct based off of the sDB and sServ arguments
Dim conStr As String = ("driver={SQL Server};server = " & sServ & " ; uid = username;pwd=password:database = " & sDB)
'Create a connection and pass it your conStr
Using con As New SqlConnection(conStr)
con.Open() 'open the connection
'create your sql statement and add the WHERE clause with a parameter for the input argument 'sJob'
Dim sql As String = "SELECT [ID], [Name] FROM dbo.PropertyTypes WHERE [Name] = #job"
'create the sqlCommand (cmd) and pass it your sql statement and connection
Using cmd As New SqlCommand(sql, con)
'add a parameter so the command knows what #job holds
cmd.Parameters.Add(New SqlParameter("#job", SqlDbType.VarChar)).Value = sJob
'Now that have the command built, we can pass it to a reader object
Using rdr As SqlDataReader = cmd.ExecuteReader
rdr.Read()
'i admin i'm a little confused here on what you are
'trying to achieve so ID may not be what you are
'really wanting to get a substring of.
Return rdr("ID").ToString.Substring(2, 36)
End Using
End Using
End Using
End Function
An example to see if this is working could be to call a messagebox do display the result. For this example, I'm going to pretend that TextBox3 holds the sJob you're wanting. With that knowledge, you could simply do:
MessageBox.Show(GetG(TextBox2.Text, TextBox1.Text, TextBox3.Text))
This should then produce the result in a messagebox.
It seems that you're not filling your DataSet. So, when you try to loop through it, it's uninitialized or empty.
Check this answer to see an example: Get Dataset from DataBase
I have names and surnames to retrieve from DB, but It's not working as It should. I get names and surnames from a table where they are in separated columns. Names/surnames are displayed in combobox/textbox combination on my form. Now I need to retrieve this data, but there are only 4 fields in my DB to search, because all names/surnames are combined together in those fields (user request). My code works for 2 searches at a time, but not for all 4. Here is my code:
EDIT (this works now - I've separated parameters and added bracket in OR statements):
Using con As New OracleConnection("Data Source=myDB;User Id=Lucky;Password=MyPassword;")
con.Open()
Using cmd As New OracleCommand()
Dim SQL As String = "Select * FROM MyTable "
Dim conca As String = " Where "
Dim Person1 As String
Person1 = CmbName.Text.Trim & " " & TxtSurname.Text.Trim
If Not CmbName.Text = "" Then
SQL = String.Concat(SQL, conca, " (USER1 = :user OR USER2 = :user1)")
cmd.Parameters.Add(New OracleParameter("user", Person1))
cmd.Parameters.Add(New OracleParameter("user1", Person1))
conca = " and "
End If
Dim Person2 As String
Person2 = CmbName1.Text.Trim & " " & TxtSurname1.Text.Trim
If Not CmbName1.Text = "" Then
SQL = String.Concat(SQL, conca, " (ADMINISTRATOR1 = :admin OR ADMINISTRATOR2 = :admin1)")
cmd.Parameters.Add(New OracleParameter("admin", Person2))
cmd.Parameters.Add(New OracleParameter("admin1", Person2))
conca = " and "
End If
'Retrieve data using execute reader
cmd.Connection = con
cmd.CommandText = SQL
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
Dim dt As New DataTable
dt.Load(dr)
DataGridView1.DataSource = dt
End Using
I tried using brackets between "and" & "or", but this still doesn't work. Any suggestions ?
Although I don't like your approach, you should separate the queries or have one function retrieving results for you for each "Person" request. For your solution try to remove this: conca = " and " from the first and second 'if/else' statement. Add each result into your datatable and then load the gridview with the datatable.
You should call a function similar to this to get the results in a data reader and then feed your datatable. This way you can separate your queries. The tricky part is to have an elegant way to load your datagridview. My suggestion is to stop using datatables (they are very bad). You should use IEnumerable or List (Of Object) where you could add the results from each query.
Public Shared Function GetMeDatareader(yourQuery As String) As OracleDataReader
Using con As New OracleConnection("Data Source=myDB;User Id=Lucky;Password=MyPassword;")
con.Open()
Using cmd As New OracleCommand()
Dim SQL As String = yourQuery
'Retrieve data using execute reader
cmd.Connection = con
cmd.CommandText = SQL
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
Return dr
End Using
End Using
End Function
I really need help this time. I search everywhere, tried numerous solutions. but i can't seem to solve my problem. Now i'm going to ask, please help. I have been having this problem for a week now.
ExecuteSQL("select * from account_database where idnum= #idnum and password= #pass")
'Dim idnum As New SqlParameter("#idnum", SqlDbType.VarChar)
'Dim pass As New SqlParameter("#pass", SqlDbType.VarChar, -1)
'idnum.Value = idnumtxt.Text
'pass.Value = output
'cmd.Parameters.Add(idnum)
'cmd.Parameters.Add(pass)
cmd.Parameters.Add("#idnum", SqlDbType.VarChar).Value = idnumtxt.Text
cmd.Parameters.Add("#pass", SqlDbType.VarChar, -1, "password").Value = output
those commented out lines are the codes which i have tried, also there are codes which i implemented that also failed.
The error message concludes as "Must declare scalar variable #idnum"
i really need help please. Please shine some light.
This is the code what the function executeSQL contains :
Public Shared Sub ExecuteSQL(ByVal strSQL As String)
Try
If connection.State = 1 Then ' check connection if open
connection.Close()
End If
' connection
connection.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
connection.Open()
Dim rowAffected As Integer = 0
'cmd = New SqlCommand(strSQL, connection) 'buiding the sql command with the use of strSQL (sql statement) and connection (database connection)
cmd = New SqlCommand(strSQL, connection)
DARec = New SqlDataAdapter(strSQL, connection) 'buiding the adapter
cb = New SqlCommandBuilder(DARec)
rowAffected = cmd.ExecuteNonQuery() 'executing of sql statement
successID = 1
connection.Close()
Catch ex As Exception
successID = 0
MsgBox(ex.Message)
End Try
End Sub
Thanks and please help.
Problem is simply you're doing this in the wrong order. You're attempting to execute your SQL statement before defining the parameters. You don't need ExecuteSQL() until you've defined your parameters. It likely breaks on the following line in ExecuteSQL()
' See how many rows the query will impact
' Since #idnum and #pass are not defined until the
' ExecuteSQL() sub is finished, this line breaks.
rowAffected = cmd.ExecuteNonQuery()
You need to build your SqlCommand() to first include the select statement, and then use AddWithValue() on the parameters you've defined in the string. Defining the datatypes is also unnecessary because your database already knows, and form validation should handle input.
' Define your connection
connection.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
' Setup your SQL Command.
cmd = New SqlCommand("select * from account_database where idnum = #idnum and password = #pass", connection)
' Define the parameters you've created
cmd.Parameters.AddWithValue("#idnum", idnumtxt.Text)
cmd.Parameters.AddWithValue("#pass", output)
' Now execute your statement
connection.open()
cmd.ExecuteNonQuery()
connection.close()
And here is a better version of the above code, since you understand the order of events now. This ensures that in the event of exception the connection is closed.
strConn = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
strSQL = "select * from account_database where idnum = #idnum and password = #pass"
Using connection As New SqlConnection(strConn), cmd As SqlCommand(strSQL, connection)
cmd.Parameters.Add("#idnum", SqlDbType.VarChar).Value = idnumtxt.Text
cmd.Parameters.Add("#pass", SqlDbType.VarChar, -1, "password").Value = output
connection.Open()
cmd.ExecuteNonQuery()
End Using
Try this:
cmd.Parameters.AddWithValue("idnum", idnumtxt.Text)
Reference:
SqlParameterCollection.AddWithValue # MSDN.
It should just be a case of the following to add an input param
cmd.Parameters.Add("#idnum", idnumtxt.Text)
Except you'll need cmd.parameters.add() before the executesql as you're currently defining your params after executesql has ran.
Dim elem As String
elem = "Grade School"
Dim v As Integer
v = 0
Dim con As New SqlConnection("SERVER=ANINGDZTS-PC;DATABASE=AEVS;Trusted_Connection = yes;")
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM tbl_Voter WHERE Department, VotersID = '" & elem & "''" & txt_PwordElem.Text & "'AND Voted ='" & v & "'", con)
con.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader()
Try
If (sdr.Read() = False) Then
high()
Else
MessageBox.Show("WELCOME!")
elemBallot.Show()
Me.Hide()
End If
Catch EX As Exception
MsgBox(EX.Message)
End Try
End Sub
this code is not working, an error appear," An expression of non-boolean type specified in a context where a condition is expected, near ','."
Instead of trying to create your SQL query via concatenating strings, which is prone to errors, a much better way is to use parametrized query. Change your SqlCommand declaration to
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM tbl_Voter WHERE Department = #Department AND VotersID = #VotersID AND Voted = #Voted", con)
cmd.Parameters.AddWithValue("#Department", elem)
cmd.Parameters.AddWithValue("#VotersID", txt_PwordElem.Text)
cmd.Parameters.AddWithValue("#Voted", v)
Bonus: Avoid SQL Injection
P.S. Please don't forget to close your Reader and Connection after the use.
P.P.S. If you simple need to make sure that specific row in table "tbl_Voter" exists or not based on your parameters (which is, judging by the code what you're doing) - using DataReader is overkill. Consider query like SELECT 1 FROM tbl_Voter ... and use of ExecuteScalar to check returned value for Nothing
Trying to select an integer from an Access Database using an SQL statement in VB
Dim cmdAutoTypes As New OleDbCommand
Dim AutoTypesReader As OleDbDataReader
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = '" & cboTypeIds.Text & "'"
AutoTypesReader = cmdAutoTypes.ExecuteReader
Error message says: "OleDbException was unhandled: Data type mismatch in criteria expression." and points to the AutoTypesReader = cmdAutoTypes.ExecuteReader line
Rather make use of OleDbParameter Class
This will also avoid Sql Injection.
You don't need the quotes in the query string. You're searching for a number, not a string.
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text
Hi In access SQL you can't use single quote around your Integer type.
so
command text will be.. "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text & " and .... "
In Access SQL, don't quote numeric constants.
And test whether IsNull(cboTypeIds). You can't do what you were planning to do until a value has been chosen.
Do not use string concatenation when you build your SQL query, use parameters instead.
Dim cmd As OledbCommand = Nothing
Dim reader as OleDbDataReader = Nothing
Try
Dim query As String = "SELECT * FROM AutoTypes WHERE TypeId = #Id"
cmd = New OledbCommand(query, connection)
//adding parameter implicitly
cmd.Parameters.AddWithValue("#Id", cboTypeIds.Text)
reader = cmd.ExecuteReader()
Catch ex As Exception
Messagebox.Show(ex.Message, MsgBoxStyle.Critical)
End Try
You can also explicitly state the parameter data type.
cmd.Parameters.Add("#Id", OleDbType.Integer).Value = cboTypeIds.Text
Hope this helps.