How to check the exist value - vb.net

Using VB.Net and Sql Server
I want to check the user Entry Value.
The User is entering the code in the textbox, before saving to the table, i want to check whethere code is already exist in the table or not.
Tried Code
cmd = New SqlCommand("Select code from table where code = '" & textbox1.Text & "' ", Con)
dr = cmd.ExecuteReader()
While dr.Read()
End While
If value is exist, then message to the user "Already Exist" other wise save to the table.
Need Vb.net Code Help

Use SELECT COUNT instead and then check for that being greater than zero:
cmd = New SqlCommand("SELECT COUNT(*) from table where code = '" & textbox1.Text & "' ", con)
Dim NumRecords as Int32 = cmd.ExecuteScalar
IF NumRecords > 0 THEN...

Make code as primary key since you want it to be unique
if the value entered by the user in code is already existing in the table , VIOLATION of primary key sql exception will be thrown
Catch that exception and display a warning message!

Related

How to check for duplicate value in database when importing vb.net

For i As Integer = 0 To dgclassinfo.Rows.Count - 1
LRN = dgclassinfo.Rows(i).Cells(2).Value.ToString
Lname = dgclassinfo.Rows(i).Cells(3).Value.ToString
Fname = dgclassinfo.Rows(i).Cells(4).Value.ToString
Mname = dgclassinfo.Rows(i).Cells(5).Value.ToString
comm.CommandText = "insert into g7(LRN,Lname,Fname,Mname ) values('" & LRN & "','" & Lname & "','" & Fname & "','" & Mname & "')"
comm.ExecuteNonQuery()
Next
I used to code above to import my data. Using dgv. My data is databound. for additional info. When I import the file it reads the value of the excel and displays in the dgv in which i insert the data using the for loop above. I think I need to use mydr.hasrows but I have no idea on how to do this using for loop. How can I check for duplicate records every row? LRN is my pk.
Any help will be appreciated.
To check if record exists, u can actually check the database's specific column to see if the column has any rows containing the same record u are trying to insert..TO do this,first u need to check the database for duplicates and then insert new data if no duplicates exist.A full example might look like this :
Dim cmd as new SqlCommand("Select * from TABLENAME([column names-remove brackets if required])values(#value1)",con)
cmd.parametres.AddWithValue("#value1",Firstname.Text)
Dim dr as new SqlDataReader=cmd.Executereader
If dr.hasRows Then 'This checks if any duplicates exist
Msgbox("Duplicates Found")
Else
Dim cmd as new SqlCommand("Inserting data query here",con)
cmd.parametres.Add("#value1",SqlDbtype.Varchar).value=Firstame.Text
cmd.ExecuteNonQuery
Here i've assumed u r using Sql Server, make necessary changes to the code

How can I insert a value in a specified column together with the other columns without appearing it into a new another row alone?

I am creating a login logout system for our College Library that records the students' time in and time out whenever they enter or exit in our library.
I am using VS 2010 Ultimate for the form and SQL server 2008 r2 for my database.
In my database
i have 3 tables
tblCollegeinfo Contains :
studentNumber(primary key),
studentName, and
studentCourse,
tblCollegeStudentLog contains their record with
studentNumber again as the foreign key,
studentTimeIn,
studentTimeOut,
studentDate and
LoginNo and
tblCollegeStudentPassword contains
their Passwords with studentNumber again
and studentPassword.
Actually my Log In button works, that whenever they entered their Username and Password and hit the Log In button they are now Logged In and their Student Number, Name, Course Login time (Time In) and Date appears in the ListView.
My problem is the Log out button. I don't know what correct code should i use. What correct SQL query should I use.
I have a hint that I should join the tables first and Insert the Log Out Time as the 'value' in the studentTimeOut of the table "tblCollegeStudentLog"
but I don't know how. Whenever I click the Log Out button with the SelectedItems in my ListView, instead the Logout Time(Time Out) inserted in the selected item it appears in another row. In short, how can I insert a value in a specified column together with the other columns without appearing into a new another row?
Please help me guys to solve this problem :( I hope you understand what I am trying to say :( I want that the inserted Value appears together with the other columns, because what only happens to me is that whenever i hit the Log Out button the value appears in another row alone it is not joining in the other columns :( thanks Guys!!!
Heres the code:
Private Sub btnLogoutNow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogoutNow.Click
Connect()
cmd = New SqlCommand("SELECT tblCollegeStudentlog.LoginNo, tblCollegeStudentLog.studentNumber, tblCollegeInfo.studentName, tblCollegeInfo.studentCourse, tblCollegeStudentLog.studentTimeIn, tblCollegeStudentLog.studentTimeOut, tblCollegeStudentLog.studentDateIn FROM tblCollegeStudentLog LEFT OUTER JOIN tblCollegeInfo ON tblCollegeStudentLog.studentNumber = tblCollegeInfo.studentNumber WHERE tblCollegeStudentLog.studentNumber = '" + lvwLog.SelectedItems(0).Text + "'", con)
cmd.ExecuteNonQuery()
If dr.HasRows Then
cmd = New SqlCommand("INSERT INTO tblCollegeStudentLog (studentTimeOut) VALUES ('" + lblTimeOut.Text + "') WHERE studentNumber = '" + lvwLog.SelectedItems(0).Text + "' ", con)
cmd.ExecuteNonQuery()
MsgBox("You are now logged out!")
End If
End Sub
You need to use UPDATE, not INSERT. Assuming they are not able to log out unless they have logged in (i.e. there is record in tblCollegeStudentLog where StudentTimeIn is NULL, you can just use:
UPDATE tblCollegeStudentLog
SET StudentTimeOut = #OutTime
WHERE StudentNumber = #StudentNumber
AND StudentTimeOut IS NULL;
Then you would use SqlParameters to properly execute the command and not leave yourself vunerable to SqlInjection, poor SQL Plan caching and data type issues:
Dim Sql as String = "UPDATE tblCollegeStudentLog SET StudentTimeOut = #OutTime WHERE StudentNumber = #StudentNumber AND StudentTimeOut IS NULL;"
Using cmd = New SqlCommand(Sql, con)
cmd.Parameters.AddWithValue("#OutTime", Convert.ToDateTime(lblTimeOutNya.Text))
cmd.Parameters.AddWithValue("#StudentNumber", lvwLog.SelectedItems(0).Text)
con.Open()
If cmd.ExecuteNonQuery() = 0 Then
'If no rows are affected then there was not a valid
'record to update, i.e. the student was not logged in
MsgBox("You were not logged in")
Else
MsgBox("You are now logged out!")
End If
End Using
N.B. Please excuse my VB.NET, I have not used it in quite some time so there may be some syntax errors.

Error in My Add button SQL Server Management Studio And Visual Basic 2010

Here is the thing I can't use insert query in my code there is an error in my SqlCommand that says the ExecuteNonQuery() not match with the values blah blah
Here is my code
Dim con As New SqlClient.SqlConnection("Server=.\SQLExpress;AttachDBFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\Finals.mdf;Database=Finals;Trusted_Connection=Yes;")
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = con
cmd.CommandText = "Insert Into [Finals].[dbo].[Nokia] Values ('" & Unit.Text & "'),('" & Price.Text & " '),('" & Stack.Text & "'),('" & Processor.Text & "'),('" & Size.Text & "'),('" & RAM.Text & "'),('" & Internal.Text & "'),('" & ComboBox1.Text & "')"
con.Open()
cmd.ExecuteNonQuery()
con.Close()
The problem is the cmd.CommandText can anyone please help me?
You need to rewrite your query to use a parameterized query. This would avoid parsing problems if your textboxes contains single quotes and, most important, would remove any possibility of Sql Injection.
So you code could look like this
Dim cmdText = "Insert Into [Finals].[dbo].[Nokia] Values (#unit, #price,#stack," & _
"#processor,#size,#ram,#internal,#lastvalue"
Using con As New SqlConnection(......)
Using cmd As New SqlCommand(cmdText, con)
con.Open()
cmd.Parameters.AddWithValue("#unit",Unit.Text )
cmd.Parameters.AddWithValue("#price",Price.Text)
cmd.Parameters.AddWithValue("#stack",Stack.Text)
cmd.Parameters.AddWithValue("#processor", Processor.Text)
cmd.Parameters.AddWithValue("#size",Size.Text)
cmd.Parameters.AddWithValue("#ram", RAM.Text)
cmd.Parameters.AddWithValue("#internal",Internal.Text)
cmd.Parameters.AddWithValue("#lastvalue", ComboBox1.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Said that, be aware of two more problems:
You don't specify a column list before the VALUES statement. This means that you need to pass the exact number of parameters for every column present in your table named Nokia AND in the EXACT ORDER of the underlying columns. If you forget one parameter you will receive an exception and if you swap the order of the parameters you end writing your data in the wrong column (with an exception waiting for you if the datatype doesn't match).
The second problem concerns the datatype of every parameter passed to the query. In your case you use the Text property of the textboxes and this means that you are passing a string for every column in the datatable. Of course, if a column expects a numeric value you get a mismatch error.
For example the #price parameter could be used to update a decimal column in the datatable and thus you need to convert the parameter from string to decimal before adding it using the AddWithValue method
cmd.Parameters.AddWithValue("#price",Convert.ToDecimal(Price.Text))

Cannot set primary key properly for table in vb.net

I've run into a bit of trouble guys. After days of labouring, debugging and researching, im on the 3rd to last line and im stuck. This isnt the full code, but the relevant parts.
Dim dbProvider As String
Dim dbSource As String
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim MaxRows As Integer
Dim sql As String
Dim TableName As String
TableName = TbTableName.Text
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM [" & TableName & "]", con)
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
Dim dsNewColoumn As DataColumn
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = E:\A2 Computing\Project\PasswordDatabase.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim TableCreate As New OleDb.OleDbCommand("CREATE TABLE [" & TableName & "](" & "ID INTEGER NOT NULL" & ")", con)
Dim NewColoumn As New OleDb.OleDbCommand("ALTER TABLE [" & TableName & "] ADD " & X & " VARCHAR(60)", con)
TableCreate.ExecuteNonQuery()
da.Fill(ds, "NewTable")
MaxRows = ds.Tables("NewTable").Rows.Count
ds.Tables("NewTable").PrimaryKey = New DataColumn() {ds.Tables("NewTable").Columns("CustID")}
X = 0
Do
X = X + 1
dsNewColoumn = ds.Tables("NewTable").Columns.Add
ds.Tables("NewTable").Columns.Add(X)
dsNewRow = ds.Tables("NewTable").NewRow()
ds.Tables("NewTable").Rows.Add(dsNewRow)
Loop Until X = 30
da.InsertCommand = cb.GetInsertCommand()
da.UpdateCommand = cb.GetUpdateCommand()
da.Update(ds, "NewTable")
End Sub
The problem im having is at this line here
da.UpdateCommand = cb.GetUpdateCommand()
The error is
Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
I understand this means my table doesnt have a primary key, but i have set one. Any help would be greatly appreciated! =)
You need the key column in the DB.
The command builder doesn't use the key you set in the datacolumn in the dataset.
In fact, if you look at the code, CB create command used by DA, but CB has no reference to your ds.Tables("NewTable").PrimaryKey, so CB will never be able to take your PrimaryKey in consideration.
So, you need to set a primary key in the DB.
Anyway, why do you have a Database table without a primary key?
Update (after reading the first 9 comments)
You define the Table columns in the TableCreate SQL command, when you execute this command it will create the table AND the column IN the database file.
A table can be empty (no rows) but MUST have at least a column.
You CAN'T use the dataset/datatable abstraction/object to add real column to the real table in the database, it doesent works this way (see point 1)
It give you the error "SSSS.ID' cannot contain a Null" because in the SQL CREATE command you are creating a table with a column called ID that is NOT NULL (see the "ID INTEGER NOT NULL" part of the command) so if you add a row to this table, the column ID MUST contain a value that is not null.
your loop is adding a column at the datatable for each iteration, it doesn't work this way, you cant do that. And if you do, you are doing it wrong.
The column "CustID" you are adding at the datatable exist only in the datatable (the "in-memory" abstraction of the real table) it will never exist in the DB (unless you add it to the CREATE TABLE command)
In my opinion you need to:
Study a good book on RDBMS and SQL (to learn the basics of how a DB works, tables, relations, key, columns, datatype, SQL, null value....)
Read some good article/book on how dataset/datatable/connection interact with a real DB

unable to find specified column in result set index out of bounds index out of range exception

i am having trouble putting a value in a textbox. Each time a ticket is sold i put the total price in a textbox, each time a ticket is sold for the same concert it increases by adding its self to the total price. It works at the first sale, but after that it breaks down. here is the code and thanks in advance.
Private Function DisplayMoneyTaken() As Integer
Dim totalMoney As Integer
'open the database connection
strSQL = "SELECT MAX(Total_Money) FROM Sales WHERE Concert_Id =" + Mid(cboVenue.Text, 1, 4)
conn.Open()
cmd.Connection = conn
cmd.CommandText = strSQL
cmd.CommandType = CommandType.Text
dr = cmd.ExecuteReader()
'read the record returned
dr.Read()
If IsDBNull(dr.Item(0)) Then
totalMoney = txtPrice.Text
Else
DisplayMoneyTaken = dr.Item("Total_Money") + Val(txtPrice.Text)
End If
'close the database
conn.Close()
Return totalMoney
End Function
It doesn't appear that your query has a column named "Total_Money". You didn't name the single column your query returns.
Michael,
When using an aggregate function, it is necessary to also assign an alias to that column.
For example
strSQL = "SELECT MAX(Total_Money) as CaChing FROM Sales WHERE Concert_Id =" + Mid(cboVenue.Text, 1, 4)
If you do not assign an alias, the server will sometimes assign one. But you have to know or guess what it will be. Its a lot better to just pick one that makes sense.
You can also index items with a number, this is what you did when you were checking for NULLs.
This same syntax could have been used when accessing the value.
DisplayMoneyTaken = dr.Item(0) + Val(txtPrice.Text)