Cheking duplicate name and insert user vb.net - vb.net

I am doing a form where the user is writing his username and choose from a button list. Before the insert i need to check if the username is already existed or not. The server side code is:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
'Duplicate username
Dim username As String = tbUsername.Text.Trim()
Dim tempUser As Byte = CByte(rblDept.SelectedIndex)
Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = #cUserName"
Dim haha As DataTable = New DataTable()
Using adapter = New SqlDataAdapter(query1, ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
adapter.Fill(haha)
If haha.Rows.Count <> 0 Then
lblmessage.Text = "Error! user name is already exist"
Return
End If
End Using
'Insert new user
Dim query As String = "Insert into Intranet.dbo.Gn_ISCoordinators (cUserName,lDeptUser) Values ('" & username & "'," & tempUser & ")"
Dim hehe As DataTable = New DataTable()
Using adapter1 = New SqlDataAdapter(query, ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
adapter1.Fill(hehe)
lblmessage.Text = "User has been added"
End Using
End Sub
So when the user press the button it first check the duplicate username if everything is ok, then it inserts the row.
Btw the error is occur when i press on submit button and it gave me this Must declare the scalar variable "#cUserName". on adapter.Fill(haha) line.
Please i want to know what is wrong with my code. Help me
Thanks in advance.

Error message shows everything you need to know to solve that issue. You're using parameter #cUserName in your query, but it is never set.
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
conn.Open()
Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = #cUserName"
Dim command As New SqlCommand(query1, conn )
Dim param As New SqlParameter()
param.ParameterName = "#cUserName"
param.Value = username
command.Parameters.Add(param)
Using adapter = New SqlDataAdapter(command)

You are using a Parameter #cUserName but you did not initialize it or pass values to it.
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
conn.Open()
Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = #cUserName"
Dim command As New SqlCommand(query1, conn)
command.Parameters.AddWithValue("#cUserName",username)
Using adapter = New SqlDataAdapter(command)

Related

Multiple User Registration Form vb.net

I have a user registration form for multiple users. This works fine except the code is unable to identify if there is already username exist. I know there is mistake in my code but I am unable to rectify that one.
Code is below can anyone help me sort this, how to write modify code for reader
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim user, pass As String
user = UsernameTextBox.Text
pass = PasswordTextBox.Text
Dim connection1 As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Credentials.mdb;")
Dim command As New OleDbCommand("SELECT [ID] FROM [Staff] WHERE [usernameField] = username AND [passwordField] = password", connection1)
Dim usernameParam As New OleDbParameter("username", Me.UsernameTextBox.Text)
Dim passwordParam As New OleDbParameter("password", Me.PasswordTextBox.Text)
command.Parameters.Add(usernameParam)
command.Parameters.Add(passwordParam)
command.Connection.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("User Exist")
MyPlayer.SoundLocation = path & LogOnsound
PasswordTextBox.Text = ""
UsernameTextBox.Text = ""
ElseIf user = "" Or pass = "" Then
MsgBox("Please Fill The Boxs", , "Error")
Else
Dim connection As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Credentials.mdb;"
Using myconnection As New OleDbConnection(connection)
myconnection.Open()
Dim sqlq As String = "INSERT INTO [staff] ([username], [password]) VALUES (#user, #pass)"
Using cmd As New OleDbCommand(sqlq, myconnection)
cmd.Parameters.AddWithValue("#usernme", user)
cmd.Parameters.AddWithValue("#passwrd", pass)
cmd.ExecuteNonQuery()
MsgBox("User Registered!", , "register")
user = ""
pass = ""
End Using
End Using
End If
command.Connection.Close()
End Sub
It looks like you have multiple things wrong:
You should be specifying #username instead of just username in your SELECT statement so that it will be recognized as a parameter.
Why are you checking for a match on password also? If you do that, people can have the same username with just a different password...do you want that?
In your SELECT, you have usernameField as the column name in your Staff table, but in your INSERT, you have username as the column name. Which is it?
In your INSERT, you specify the parameter #user, but in your cmd.Parameters.AddWithValue statement, you have #usernme.

Visual basic - Incrementing the score

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using

Authentication to host user failed - Using Password NO - VB.NET

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.

Preparing a Query in VB.NET

I have troubles preparing a query with 2 parameters in VB.NET.
This is my code:
Dim username As String = loginUsername.Value
Dim password As String = EncryptMD5standard(loginPassword.Value)
Dim valid As Boolean = False
Dim connectionString As String = ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString
Dim queryString As String = "SELECT id, user_name, role FROM users WHERE user_name = '#user' AND paswd = '#pass'"
Dim ds As New DataSet()
Try
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
command.CommandText = queryString
command.Parameters.Add("#user", SqlDbType.NVarChar, 15).Value = username
command.Parameters.Add("#pass", SqlDbType.NVarChar, 32).Value = password
Dim adapter As New SqlDataAdapter()
adapter.SelectCommand = command
adapter.Fill(ds, "login")
If ds.Tables("login").Rows.Count > 0 Then
valid = True
End If
End Using
Catch ex As Exception
errorLabel.Text = DirectCast(GetLocalResourceObject("erroreDB"), String) & ": " & ex.ToString
End Try
But, by doing this my valid value is always "false", so it fails the row count.
I used some debug and looks like my table login inside ds is empty.
Query works, I tried it manually in SQLServer replacing parameters and I can't understand why I have empty results.
What I'm doing wrong?.
You don't need to wrap your parameters in single quotes, as the parameter system takes care of that.

Vb.Net and CSV files

I have a VB.Net app that should enable the user to import CSV file into the datagrid (which it does) and then update those rows to a table in Oracle.
Here is what I have so far but it doesn't seem to work neither throw an error.
Private Sub Update_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Update.Click
MsgBox("Saving...")
Dim table As New DataTable()
Dim BindingSource As New BindingSource()
BindingSource.DataSource = table
table.Columns.Add("ORDER_NO")
table.Columns.Add("LINE_ITEM_NO")
table.Columns.Add("CONTRACT")
table.Columns.Add("PART_NO")
table.Columns.Add("QTY_REQUIRED")
table.Columns.Add("QTY_PER_ASSEMBLY")
table.Columns.Add("RELEASE_NO")
table.Columns.Add("SEQUENCE_NO")
table.Columns.Add("ORDER_CODE")
table.Columns.Add("PART_OWNERSHIP")
Dim parser As New FileIO.TextFieldParser("C:\Documents and Settings\User\Desktop\solution.csv")
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True
parser.TrimWhiteSpace = True
parser.ReadLine()
Dim sConnectionString As String = "Data
Source=MYSERVER.COM;User ID=MYNAME;Password=MYPASSWD;"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOC_TAB(ORDER_NO,
LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY,
RELEASE_NO,SEQUENCE_NO,ORDER_CODE,PART_OWNERSHIP) VALUES (#ORDER_NO,
#LINE_ITEM_NO,#CONTRACT,#PART_NO,#QTY_REQUIRED,#QTY_PER_ASSEMBLY,#RELEASE_NO,#SEQUENCE_NO,#ORDER_CODE,#PART_OWNERSHIP)"
Using conn As New OracleClient.OracleConnection(sConnectionString)
Dim adapter As New OracleDataAdapter
Dim cmd As New OracleClient.OracleCommand()
cmd.Connection = conn
cmd.Connection.Open()
cmd.CommandText = strSql
adapter.InsertCommand = New OracleCommand(strSql, conn)
adapter.UpdateCommand = cmd
adapter.Update(table)
'--cmd.ExecuteReader()
cmd.Connection.Close()
MsgBox("Saved! Kindly check your Shop order!")
DataGridView1.DataSource = Nothing
End Using
End Sub
Now I have brought it down to inserting records in the table, but problem is it only parses the first column in the row.
So all suppose 6 columns in the table are updated with values from the first field in the CSV.
MsgBox("Saving...")
Dim parser As New FileIO.TextFieldParser("C:\Documents and Settings\nUser\Desktop\solution.csv")
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True
parser.TrimWhiteSpace = True
Dim i As Integer
For i = 0 To DataGridView1.RowCount - 1
Dim CurrentField = parser.ReadFields()
'--parser.ReadLine()
Dim sConnectionString As String = "Data Source=MYSERVER.COM;User ID=MYUSER;Password=MYPASSWD;"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOCT(ORDER_NO, LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY) VALUES (:ORDER_NO, :LINE_ITEM_NO,:CONTRACT,:PART_NO,:QTY_REQUIRED,:QTY_PER_ASSEMBLY)"
Using conn As New OracleClient.OracleConnection(sConnectionString)
Using cmd As New OracleClient.OracleCommand()
Dim adapter As New OracleDataAdapter
conn.Open()
cmd.Connection = conn
cmd.CommandText = strSql
cmd.Parameters.AddWithValue("ORDER_NO", CurrentField(i))
cmd.Parameters.AddWithValue("LINE_ITEM_NO", CurrentField(i))
cmd.Parameters.AddWithValue("CONTRACT", CurrentField(i))
cmd.Parameters.AddWithValue("PART_NO", CurrentField(i))
cmd.Parameters.AddWithValue("QTY_REQUIRED", CurrentField(i))
cmd.Parameters.AddWithValue("QTY_PER_ASSEMBLY", CurrentField(i))
cmd.CommandText = strSql
adapter.InsertCommand = New OracleCommand(strSql, conn)
adapter.UpdateCommand = cmd
'adapter.Update(table)
cmd.ExecuteNonQuery()
cmd.Connection.Close()
DataGridView1.DataSource = Nothing
End Using
End Using
Next
Never used oracle so please ignore me if I'm being stupid.
Have you tried conn.Connect() rather than cmd.Connection.Open()?
I don't understand the part of your code that create a DataTable and add columns.
It's not used anywhere, so is not related to your issue.
Let's look at code relating data connection
' If I remember well, the parameters in an oracle statement are prefixed by a ":"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOC_TAB(ORDER_NO," +
"LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY, " +
"RELEASE_NO,SEQUENCE_NO,ORDER_CODE,PART_OWNERSHIP) VALUES (:ORDER_NO, " +
":LINE_ITEM_NO,:CONTRACT,:PART_NO,:QTY_REQUIRED,:QTY_PER_ASSEMBLY, " +
":RELEASE_NO,:SEQUENCE_NO,:ORDER_CODE,:PART_OWNERSHIP)"
' Connection and Command are Disposable, so use `Using` around them
Using conn As New OracleClient.OracleConnection(sConnectionString)
Using cmd As New OracleClient.OracleCommand()
Dim adapter As New OracleDataAdapter
conn.Open()
cmd.Connection = conn
cmd.CommandText = strSql
' Now you need to add the parameters to your command
' One parameter for each column used in the insert statement
' I suppose that values for the paramenter are in the current line from your CSV
cmd.Parameters.Add("ORDER_NO", OracleType.VarChar).Value = parser[index_of_orderNumber_Text])
' .... other parameters to be added....
' Now you can execute the INSERT statement directly with your command
cmd.ExecuteNonQuery()
End Using
And, as last thing, the OracleClient namespace has been deprecated by Microsoft, so you should try to replace with ODP directly from Oracle.