I ask here because I'm having a problem with my code.
It's suppose to update an SQL Database but instead it shows an error which is
Key cannot be null. Parameter name: key
It highlights the SQLConnection.Open()
Private Sub btnTakeQuiz_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnTakeQuiz.Click
Dim SQLStatement As String = "UPDATE class SET exam=Yes WHERE name = " & Session("name") & ""
TakeQuiz(SQLStatement)
End Sub
Public Sub TakeQuiz(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
SQLConnection.Open()
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
SQLConnection.Dispose()
Server.Transfer("Quiz.aspx", True)
End Sub
Session("name") Contains the current login user name.
Class is my table.
exam is a column if it's yes then it means the user has took an exam.
What I'm trying to do is to limit a user to one quiz only. Can anyone help me?
The "Yes" and session value will be treated as a column or data source which will give a query like this.
UPDATE class SET exam=Yes WHERE name = <SessionValue>
Can you try this?
Dim SQLStatement As String = "UPDATE class SET exam='Yes' WHERE name = '" & Session("name") & "'"
Related
I am making a work management system and I am fairly new to Visual Basic.
What I am trying to do is retrieve the name of the employee from the database with the given ID. After that I want this name to be displayed in a Label. After that, he can press the Work Start or Work end buttons.
Here is the code:
Private Function employeeSearchwithID(PersonalNr As String) As String
Dim mitarbeiter As String
Dim r As DataRow
Access.ExecQuery("SELECT [Vorname], [Name] from [TA-Personal] WHERE ([Personal_Nr] = '" & PersonalNr & "');")
'Report and Abort on Erros or no Records found
If NoErros(True) = False Or Access.RecordCount < 1 Then Exit Function
r = Access.DBDT.Rows(0)
'Populate Label with Data
mitarbeiter = r.Item("Vorname") & " " & r.Item("Name")
Return mitarbeiter
End Function
It is used like this:
Private Sub tbxUserInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbxUserInput.KeyDown
If e.KeyCode = Keys.Enter Then 'employeeIDnumbersSelect()
Label5.Text = employeeSearchwithID(tbxUserInput.ToString)
End If
End Sub
So, the plan is to have this program running on a tablet connected to a scanner. Every employee will have a personal card. When they scan the card, I want their names to be displayed. Of course, the card will be with the ID. But I am having trouble with the names: when I give my personal number it comes up as an empty string.
I have a separate DB Module. I learned from a tutorial:
Imports System.Data.OleDb
Public Class DBControl
' DB Connection
Public DBCon As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\recycle2000.mdb;")
'DB Command
Public DBCmd As OleDbCommand
'DB Data
Public DBDA As OleDbDataAdapter
Public DBDT As DataTable
'Public Myreader As OleDbDataReader = DBCmd.ExecuteReader
'Query Paramaters
Public Params As New List(Of OleDbParameter)
' Query Stats
Public RecordCount As Integer
Public Exception As String
Public Sub ExecQuery(Query As String)
'Reset Query Stats
RecordCount = 0
Exception = ""
Try
'Open a connection
DBCon.Open()
'Create DB Command
DBCmd = New OleDbCommand(Query, DBCon)
' Load params into DB Command
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
' Clear params list
Params.Clear()
' Execute command & fill Datatable
DBDT = New DataTable
DBDA = New OleDbDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = ex.Message
End Try
' Close your connection
If DBCon.State = ConnectionState.Open Then DBCon.Close()
End Sub
' Include query & command params
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New OleDbParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
Without knowledge of the Access class, I have to recommend a different approach to querying the database. It is important to make sure that the database is not vulnerable to SQL injection, be it deliberate or accidental. The way to do that is to use what are known as SQL parameters: instead of putting the value in the query string, the value is supplied separately.
Private Function EmployeeSearchwithID(personalNr As String) As String
Dim mitarbeiter As String = String.Empty
Dim sql = "SELECT [Vorname], [Name] from [TA-Personal] WHERE [Personal_Nr] = ?;"
Using conn As New OleDbConnection("your connection string"),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#PersonalNr",
.OleDbType = OleDbType.VarChar,
.Size = 12,
.Value = personalNr})
conn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.Read() Then
mitarbeiter = rdr.GetString(0) & " " & rdr.GetString(1)
End If
End Using
Return mitarbeiter
End Function
Private Sub tbxUserInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbxUserInput.KeyDown
If e.KeyCode = Keys.Enter Then 'employeeIDnumbersSelect()
Dim employeeName = EmployeeSearchwithID(tbxUserInput.Text.Trim())
If String.IsNullOrEmpty(employeeName) Then
MessageBox.Show("Not found.", "Problem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
Label5.Text = employeeName
End If
End If
End Sub
The Using command makes sure that the "unmanaged resources" involved in querying a database are cleaned up afterwards, even if something goes wrong.
You will need to change the value of OleDbType.VarChar and .Size = 12 to match the type and size of that column in the database.
The name of the parameter is only for convenience with OleDb because it is ignored in the actual query, which uses "?" as a placeholder. Please see OleDbCommand.Parameters Property for full information.
If it still does not work, then please enter the ID manually in the tbxUserInput and see if you can make it work that way.
Hang on... tbxUserInput.ToString should be tbxUserInput.Text. But everything else I wrote still applies.
Imports MySql.Data.MySqlClient
Public Class Form1
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim con As MySqlConnection = JOKENCONN()
Public Function JOKENCONN() As MySqlConnection
Return New MySqlConnection("server=localhost; user id=root; password=; database =studentdb")
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GroupBox1.Enabled = False
End Sub
Private Sub LBLLOGIN_CLICK(sender As Object, e As EventArgs) Handles lbllogin.Click
lbllogin.Text = "Login"
lbllogin.Text = "Login"
lblname.Text = "Hi, Guest"
If lbllogin.Text = "Login" Then
GroupBox1.Enabled = True
End If
End Sub
Private Sub BTNOK_CLICK(sender As Object, e As EventArgs) Handles btnok.Click
Dim Sql As String
Dim publictable As New DataTable
Try
If txtusername.Text = "" And txtpass.Text = "" Then
MsgBox("Password or username is incorrect!")
Else
Sql = "select ' from tbluseraccount where username='" & txtusername.Text & "' and userpassword='" & txtpass.Text & "'"
With cmd
.Connection = con
End With
da.SelectCommand = cmd
da.Fill(publictable)
If publictable.Rows.Count > 0 Then
Dim user_type As String
user_type = publictable.Rows(0).Item(4)
Name = publictable.Rows(0).Item(1)
If user_type = "Admin" Then
MsgBox("Welcome " & Name & "you login as Administrator")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
ElseIf user_type = "cetakoradi2" Then
MsgBox("Welcome " & Name & "you login as cetakoradi2")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
Else
End If
Else
MsgBox("contact administrator to register")
txtusername.Text = ""
txtpass.Text = ""
End If
da.Dispose()
End If
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
End Class
this the error i received
ExecuteReader CommandText property has not been properly initialized
i really need help on that. this is the error that i receives. thank you
Assuming that the name of the field represented in publictable.Rows(0).Item(4) is named user_type, then you could use the following:
'Declare the object that will be returned from the command
Dim user_type As String
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = JOKENCONN()
'Create a new instance of the command object
Using cmd As OleDbCommand = New OleDbCommand("SELECT user_type FROM tbluseraccount WHERE username=#0 AND userpassword=#1;", con)
'Paramterize the query
cmd.Parameters.AddWithValue("#0", txtusername.Text)
cmd.Parameters.AddWithValue("#1", txtpass.Text)
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
user_type = cmd.ExecuteScalar()
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
If (String.IsNullOrWhitespace(user_type)) Then
'Failed login
ElseIf (user_type = "Admin") Then
'Admin login
ElseIf (user_type = "cetakoradi2") Then
'cetakoradi2 login
Else
'Not a failed login, but also not an admin or cetakoradi2 either
End If
What this code does is setup a parameterized query to get just the user_type where the username and password match the parameterized values. Since there should only ever be one record that matches those conditions (presumably) then we're able to use ExecuteScalar to return just that single field value.
Just to reinforce the point, MySqlCommand.ExecuteScalar, just like the Microsoft counterparts, "executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored" and returns " The first column of the first row in the result set, or a null reference if the result set is empty ".
The proposed code by #David checks for this condition using IsNullOrWhitespace.
ExecuteScalar is effective but retrieves only one value at a time.
The other option pursued by the OP is to return a datarow, which is a valid approach if he wants to return several fields at the same time. In his example he retrieves two fields for variables user_type and Name respectively.
Be careful, VB.net like any other programming language has reserved keywords. If you do not take a habit of using good naming conventions you might one day stumble upon on one of those keywords, possibly hit obscure bugs. Name is not a good name for a variable and has the potential for confusion since every object has a name property.
To address the specific issue at hand, the error message ExecuteReader CommandText property has not been properly initialized is self-explanatory. What should have been done is simply:
With cmd
.Connection = con
.CommandText = Sql
End With
You defined a command, but did not tell it what to do. In your code variable Sql is defined but unused. With this missing bit there is a chance the code will work as expected.
Small details:
Not critical, but his condition does not work if you enter whitespace for example:
If txtusername.Text = "" And txtpass.Text = "" Then
An improvement is to simply trim the values from the textboxes:
If txtusername.Text.Trim = "" And txtpass.Text.Trim = "" Then
But I think what you want is not an And but Or. I don't think you want to allow logins without passwords.
Instead of doing multiple If/ElseIf you could have a Select Case
I am encountering an error where it is stating:
authentication to host '' for user '' using method 'mysql_native_password' failed with message: access denied for user ''#'localhost' (using password: no)
Now I read online about checking my passwords, my connection strings, and IP address. I have checked them all. I even checked the user privileges on my database and I have all access and every ability to modify, delete, update, and insert the database.
What is weird is that, it is only this set of code that it will not execute (This code should run when I add a new record):
Private Sub PolicyEnableFields()
'Automate Last Modified By textbox
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTable As New DataTable
Dim sqlText As String = "select full_name from user_privileges where user_name='" & Login.UserIDTextBox.Text & "'"
With sqlCommand
.CommandText = sqlText
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTable)
End With
For i = 0 To sqlTable.Rows.Count - 1
Me.PolicyModifiedTextBox.Text = (sqlTable.Rows(i)("full_name"))
Next
sqlTable.Dispose()
sqlCommand.Dispose()
sqlAdapter.Dispose()
End Sub
But when I run the exact some piece of code in a different SUB it works perfectly fine (This code runs when I edit a existing record):
Private Sub PolicyEditButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PolicyEditButton.Click
'Automate Last Modified By textbox
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTable As New DataTable
Dim sqlText As String = "select full_name from user_privileges where user_name='" & Login.UserIDTextBox.Text & "'"
With sqlCommand
.CommandText = sqlText
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTable)
End With
For i = 0 To sqlTable.Rows.Count - 1
Me.PolicyModifiedTextBox.Text = (sqlTable.Rows(i)("full_name"))
Next
sqlTable.Dispose()
sqlCommand.Dispose()
sqlAdapter.Dispose()
End Sub
HERE is my connection STRING (of course I will not show my PW):
Public sqlConnect As String = "server=10.0.7.30; userid=Alliance; password=*******; database=mydb; convert zero datetime=True"
Can anyone help?
Check the sConnection, and make sure it is initialized with the proper connection string. The error message mentions localhost, but the connection string you show is 10.0.7.30.
I am trying to query a SQL DB using a textbox field and retreive a column from the DB and store it in a variable so I can use it in other places within my site. My web form requires the user to enter a few items such as name and zip code.
My database has 3 columns; email address, zip code, and id. I need the input form to query the database and return the "email address" that matches the user's inputted "zip code"
I understand the SQL SELECT statement and the connection string is correct. My queries are working, I just can't seem to figure out how to get the returned "email address" to store in a variable. Any help would be appreciated.
Dim strconnection As String, strSQL As String, strZipCheck As String
Dim objconnection As OleDbConnection = Nothing
Dim objcmd As OleDbCommand = Nothing
Dim RREmail As String = Nothing
Dim zipQuery As String = zipCodeBox.Text
'connection string
strconnection = "provider=SQLOLEDB;Data Source=XXX.XXX.XXX.XXX;Initial Catalog=XXXXXXX;User ID=XXXX;Password=XXXXXXXX;"
objconnection = New OleDbConnection(strconnection)
objconnection.ConnectionString = strconnection
'opens connection to database
objconnection.Open()
strSQL = "SELECT [EMAIL ADDRESS] FROM ZIPCODEDATA WHERE [ZIP CODE] = #ZIP CODE "
objcmd = New OleDbCommand(strSQL, objconnection)
RREmail = CType(objcmd.ExecuteScalar(), String)
lblRREmail.Text = RREmail
objconnection.Close()
While the other comments do point out particular deficiencies with your syntax, I would like to address the question of storing a variable and take it a bit further. I generally do not use parameterized connections unless I am calling stored procedures and need an output parameter. Instead, here is what I often do to create a database connection and get my results.
First I create a public class called dbConn so I dont have to write it out a million times.
Imports System.Data.SqlClient
Public Class dbConn
Public Property strSQL As String
Private objConn As SqlClient.SqlConnection = _
New SqlClient.SqlConnection("Data Source=(local)\dev;Initial Catalog=testDataBase;Persist Security Info=False;Integrated Security = true;")
Public Function getDt() As DataTable
Dim Conn As New SqlClient.SqlConnection
Dim da As SqlClient.SqlDataAdapter
Dim dt As New DataTable
Try
objConn.Open()
da = New SqlClient.SqlDataAdapter(strSQL, objConn)
da.Fill(dt)
da = Nothing
objConn.Close()
objConn = Nothing
Catch ex As Exception
objConn.Close()
objConn = Nothing
End Try
Return dt
End Function
End Class
Then from another class (lets assume its form1) I call up that function to get a datatable returned to me. In this case I select TOP 1 to save your sanity in case by chance there is more than one email address per zip code.
Public sub getdata()
Dim strEmailAddress As String = Nothing
Dim dt As New DataTable
Dim da As New dbConn
da.strSQL = " select top 1 [email address] from [zipcode] " _
& " where [zip code] = '" & strZipCode & "'" _
& " order by [email address] asc"
dt = da.getDt
If dt.Rows.Count > 0 Then
If Not IsDBNull(dt.Rows(0)(0).ToString) Then
strEmailAddress = dt.Rows(0)(0).ToString
End If
End If
End Sub
From there you can use strEmailAddress within the sub after it is set, or you can move the string declaration outside of the sub as a public string declaration to use it elsewhere, or you can create other classes like an email class with a public property for strEmailAddress to pass it off to, etc.
I hope something in there helps you understand how to deal with your problem.
I have a table in MS Access which has a colum named NameC (using ODBC to connect to MS Access)
I want the result of the following query to be saved in a txtField
Dim query = "SELECT NameC FROM Table WHERE ClientID = " & Integer.Parse(clientID)
How to do that in VB.NET?
I have a txtNameC.Text field
I currently was reviewing some sample code and they do:
Dim _consultationTable As DataTable
Public Sub Load()
Dim query = "SELECT * FROM Table WHERE ClientID = " & Integer.Parse(clientID)
Me._consultationTable = DatabaseFunctions.GetDataTable(query)
dvgInfo.Rows.Clear()
For Each dtRow In Me._consultationTable.Rows
dvgInfo.Rows.Add()
dvgInfo.Rows.Add(dvgInfo.RowCount-1).Cells("ColClientID").Value = dtRow("ClientId").ToString()
Next
but I do not want to fill a table I just want to get the result of a query into a text box
How can I do this?
I want to do something like this but just return a value and save it into a textbox
Protected Sub BindData()
strSQL = "SELECT * FROM customer"
Dim dtReader As OdbcDataReader
objCmd = New OdbcCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
'*** BindData to GridView ***'
myGridView.DataSource = dtReader
myGridView.DataBind()
dtReader.Close()
dtReader = Nothing
End Sub
Protected Sub BindData()
strSQL = "SELECT SpecificValue FROM customer where x = y..."
Dim dtReader As OdbcDataReader
objCmd = New OdbcCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
'*** BindData to GridView ***'
myGridView.DataSource = dtReader
myGridView.DataBind()
dtReader.Close()
dtReader = Nothing
End Sub
use DataReader.populate ur data from database in the datareader & from the the datareader u can use perticular values.
i don't know your code,that's why i m giving one simple example.
here is one example.
imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim oledbCnn As OleDbConnection
Dim oledbCmd As OleDbCommand
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"
sql = "Your SQL Statement Here like Select * from product"
oledbCnn = New OleDbConnection(connetionString)
Try
oledbCnn.Open()
oledbCmd = New OleDbCommand(sql, oledbCnn)
Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader()
While oledbReader.Read
MsgBox(oledbReader.Item(0) & " - " & oledbReader.Item(1) & " - " & oledbReader.Item(2))
End While
oledbReader.Close()
oledbCmd.Dispose()
oledbCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class