i want write update statement in code behind in vb.net.if ICCID is exists in tbl_ICCID then change status from 0 to 1 and Pic_Correct_ICCID.visible=true, if not exists , display "Not found".
i wrote this code but doesnt work and for all of ICCID that not exists in Tbl_ICCID Pic_Correct_ICCID.visible=true.
Please check my code and solve my problem.
in Cls_ICCID:
Public Function Update_Status(ByVal ICCID_No As String, ByVal status As Integer) As String
Try
Dim cmd As SqlCommand
Dim sql As String
Dim sql2 As String
Dim myConnection As SqlConnection = New SqlConnection()
myConnection.ConnectionString = "Data Source=TEHRANI\TEHRANI;Initial Catalog=GSMProduction;Persist Security Info=True;User ID=sa;Password=1"
**sql = "UPDATE Tbl_ICCID SET Status='" & status & "' Where ( ICCID = '" & ICCID_No & "' )"**
myConnection.Open()
cmd = New SqlCommand(sql, myConnection)
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Update_Status = ""
Catch ex As SqlException
Update_Status = "Not found"
Catch ex As Exception
Update_Status = "Not connect to server"
End Try
End Function
in Frm_Packing
Private Sub Txt_ICCID_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Txt_ICCID.TextChanged
Pic_BP_Correct.Visible = False
Pic_BP_Wrong.Visible = False
Try
If Txt_ICCID.Text.Length = Txt_ICCID.MaxLength Then
lblError.Text = clsICCID.Update_Status(Txt_ICCID.Text.ToString(), 1)
lblError.ForeColor = Color.Red
stream = New System.IO.MemoryStream
pic_barcode = Nothing
cls.btnEncode(pic_barcode, Txt_ICCID.Text.Trim)
pic_barcode.Save(stream, System.Drawing.Imaging.ImageFormat.Png)
f = New IO.FileStream("C:\test55.png", IO.FileMode.Create, IO.FileAccess.ReadWrite)
b = stream.ToArray
f.Write(b, 0, b.Length)
f.Close()
Dim Val() = {stream.ToArray, Txt_ICCID.Text.Trim}
ds.Tables(0).Rows.Add(Val)
crp_report.SetDataSource(ds.Tables(0))
frm_crp.CrystalReportViewer1.ReportSource = crp_report
If lblError.Text = "" Then
Pic_BP_Correct.Visible = True
GBDoubleCheck.Visible = True
Txt_LabelBarcode.Focus()
Else
Pic_BP_Wrong.Visible = True
End If
End If
Catch ex As Exception
Pic_BP_Wrong.Visible = True
End Try
End Sub
Most probably due to sending status column value as string instead of int. You should remove those single-quotes. Also, this is really really bad practice to concat queries like that. Use CommandBuilders kind of thing or Typed DataSets for saving yourself against SQL injections.
Related
Hello I have a simple method to update customer details in one of my database tables however when i try to update it an error occurs saying the database is locked. I have no idea how to fix this because my add and delete queries work just fine.
This is the error message:
System.Data.SQLite.SQLiteException: 'database is locked
database is locked'
Public Sub updateguest(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN UPDATED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Dim usql As String = "UPDATE Customers SET fname = '" & txtFName.Text & "'" & "WHERE CustomerID ='" & txtSearchID.Text & "'"
updateguest(usql)
End Sub
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
Dim msql, msql1 As String
Dim con As New SQLiteConnection(ConnectionString)
con.Open()
msql = "SELECT * FROM Customers Where Fname Like '" & txtSearchName.Text & "%'"
msql1 = "SELECT * FROM Customers Where CustomerID '" & txtSearchID.Text & "'"
Dim cmd As New SQLiteCommand(msql, con)
Dim cmd1 As New SQLiteCommand(msql1, con)
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
Dim mdr As SQLiteDataReader = cmd.ExecuteReader()
If mdr.Read() Then
If txtSearchName.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE fname LIKE'" & txtSearchName.Text & "%'"
Dim con1 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con1)
con1.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con1.Close()
txtSearchID.Clear()
ElseIf txtSearchID.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE CustomerID ='" & txtSearchID.Text & "'"
Dim con2 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con2)
con2.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con2.Close()
txtSearchName.Clear()
End If
Else
MsgBox("No data found")
End If
End Sub
Private Sub IbtnDelete_Click(sender As Object, e As EventArgs) Handles ibtnDelete.Click
Dim dsql As String = "DELETE FROM customers WHERE customerid = " & txtSearchID.Text & ""
deleteme(dsql)
updatedgv(dgvCustomerInfo)
txtSearchID.Clear()
txtSearchName.Clear()
End Sub
Public Sub deleteme(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN DELTED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN DELTED!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
You made a good start on keeping your database code separate from you user interface code. However, any message boxes should be shown in the user interface and any sql statements should be written in the data access code.
I used Using...End Using blocks to ensure that database objects are closed and disposed. I used parameters to protect against sql injection. I am not too sure of the mapping of DbType types to Sqlite types. You might have to fool with that a bit. In you original Update statement you had the ID value in quotes. This would pass a string. When you use parameters, you don't have to worry about that or ampersands and double quotes. Just one clean string.
Private ConStr As String = "Your connection string"
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
End Using
Return Result
End Function
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
How can I get rid of:
System.InvalidCastException: 'Conversion from string "Type" to type
'Integer' is not valid.'"
On the line:
Dim usertype = Reader.GetString("Type")
This is my full code:
Private Sub OKbt1_Click(sender As Object, e As EventArgs) Handles OKbt1.Click
Call Connect() ' [ connection to module ]'
Dim Reader As SqlDataReader
Try
Dim command As New SqlCommand("select * from uinfo where password = '" & PASStb2.Text & "'", sqlConn)
Reader = command.ExecuteReader
Reader.Read()
Dim count As Integer = 0
While Reader.Read
count = count + 1
End While
If count = 1 Then
' ** MY ERROR **
Dim usertype = Reader.GetString("Type")
If usertype = "admin" Then
'MsgBox("username and password are correct")
MAIN_MENU.Show()
For a = 0 To 500
Next
Me.Hide()
sqlConn.Close()
sqlConn.Dispose()
ElseIf usertype = "user" Then
For a = 0 To 500
Next
Me.Hide()
'MsgBox("username and password are correct")
USERMENU.Show()
End If
ElseIf count > 1 Then
MsgBox("username and password are duplicate")
Else
MsgBox("username and password are not correct")
End If
sqlConn.Close()
Catch ex As SqlException
MsgBox(ex.Message)
Finally
sqlConn.Dispose()
End Try
End Sub
SqlDataReader.GetString Method (Int32) needs an integer (column index) as a parameter. So you need
Dim usertype as String = Cstr(Reader("Type"))
or
Dim usertype = Reader.GetString(Reader.GetOrdinal("Type"))
or
Dim usertype = Reader.GetFieldValue(Of String)("Type")
Be aware that non of those posibilites can handle DBnull.
'Reader.GetString' accepts an integer parameter, not a string. Or, do
Reader.Item("Type").ToString()
Declare usertype as Dim usertype as String and then assign value to it like usertype = Reader.Item("Type").ToString().
also you need to check value return by Reader.GetString("Type") it might be null. Turn "Option Strict" On It will help in the long run.
**Dim usertype = Reader.GetString("Type") // MY ERROR**
You are passing a value of string which obviously is wrong
GetString function accepts integer.
You might want to instantiate a data which is integer and pass it through getstring.
Dim usertype = Reader.GetString(data)
Use parameters. I let the server do the counting. Saves you some lines of code.
Private Sub OKbt1_Click(sender As Object, e As EventArgs) Handles OKbt1.Click
Call Connect() ' [ connection to module ]'
Dim Reader As SqlDataReader
Try
Using cmd As New SqlCommand("select usertype, Count(*) from uinfo Group By usertype where [password] = #password;", sqlConn)
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = PASStb2.Text
Reader = cmd.ExecuteReader()
If Reader.HasRows Then
Reader.Read()
Dim usertype As String = Reader.GetString(0)
Dim count As Integer = Reader.GetInt32(1)
If count = 1 Then
If usertype = "admin" Then
MAIN_MENU.Show()
Hide()
ElseIf usertype = "user" Then
USERMENU.Show()
Hide()
End If
ElseIf count > 1 Then
MsgBox("username and password are duplicate")
End If
Else
MsgBox("username and password are not correct")
End If
End Using
Catch ex As Exception
MsgBox(ex.Message)
Finally
sqlConn.Close()
sqlConn.Dispose()
End Try
End Sub
It is because you may not getting data from "Reader" object properly
Try this instead :
Dim command As SqlCommand = New SqlCommand("SELECT * FROM uinfo WHERE password = '" & PASStb2.Text & "'", connection)
connection.Open()
Dim READER As SqlDataReader = command.ExecuteReader()
If READER.HasRows Then
While READER.Read()
Console.WriteLine("{0}" & vbTab & "{1}", READER.GetInt32(0), READER.GetString(1))
End While
Else
Console.WriteLine("No rows found.")
End If
READER.Close()
I want to get the privilege if it's admin or encoder but with this code I can't get any value... this is my code please help me
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
cn = New MySqlConnection
cn.ConnectionString = "server=localhost; userid=root; database=dp_inventory;"
Dim reader As MySqlDataReader
Try
cn.Open()
Dim sql As String
sql = "Select from dp_inventory.user_account where employeeID='" & UsernameTextBox.Text & "' and password='" & PasswordTextBox.Text & "' "
cmd = New MySqlCommand(sql, cn)
reader = cmd.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
Dim users As String
users = "select privilege from user_account where employeeID='" & UsernameTextBox.Text & "'"
If count = 1 Then
If users = "admin" Then
frmAdminMain.Show()
ElseIf users = "encoder" Then
MainForm.Show()
End If
ElseIf count > 1 Then
frmAdminMain.Show()
Else
MsgBox("tryy again")
End If
Catch ex As Exception
MsgBox("Try again")
End Try
End Sub
There are quite a few errors in this code you wrote. Your first issue is you are simply trying to count without actually using a Sql counter.
Take a look at a code snippet from one of my applications here for a general idea
SelectStr = "SELECT MagPieces_Number,MagOperators_Number,MagFactor_Number,MagTotal_Number" & _
" FROM Parts_Mag WHERE Quote_Number_Id = #QuoteId and Quote_Rev_Id = #RevId and Part_Number_Id = #PartID and Part_Numeral_Id = #PartNumeral and SiteLocation = #Site"
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#QuoteId", QuoteId)
SqlDataCmd.Parameters.AddWithValue("#RevId", RevId)
SqlDataCmd.Parameters.AddWithValue("#PartId", PartNumber)
SqlDataCmd.Parameters.AddWithValue("#PartNumeral", PartNumeral)
SqlDataCmd.Parameters.AddWithValue("#Site", SiteLocation)
SqlReader = SqlDataCmd.ExecuteReader
While SqlReader.Read
MagPieces = SqlReader("MagPieces_Number").ToString
MagOperators = SqlReader("MagOperators_Number").ToString
MagFactor = SqlReader("MagFactor_Number").ToString
MagTotal = SqlReader("MagTotal_Number").ToString
End While
MagParticle.txtPiecesPerHour.Text = MagPieces
MagParticle.txtOperators.Text = MagOperators
MagParticle.txtMatFactor.Text = MagFactor
MagParticle.labMagTotal.Text = MagTotal
Catch ex As Exception
ErrorMessage(ex.message)
SqlReader.Close()
End Try
SqlReader.Close()
If you are simply looking for if your select statement has "Admin" or "Encoder" at the end, it would simply be something like this:
Dim empId as String = UsernameTextbox.Text
Dim SelectStr as String = "Select privilege from dp_inventory.user_account where employeeID=#empId
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#empId", empId)
Then read it with a reader. Once you have the general idea you should be able to take it from there! Im not quite sure why you need the count to begin with so you may want to just negate that portion out and simply read from your table based on the ID
now am trying to make a gridview of a database table named UploadProject.while selecting row of gridview display image in seperate image field by using imageurl At the time of compiling of following code image not displayed.an error occured..."incorect syntax near '='".Any body please help me to solve this problem
Protected Sub OnSelectedIndexChanged(sender As Object, e As System.EventArgs) Handles GridView1.SelectedIndexChanged
Dim row As GridViewRow = GridView1.SelectedRow
lblimageid.Text = row.Cells(0).Text
lbltitle.Text = row.Cells(1).Text
get_Address()
get_Image()
End Sub
Public Sub get_Address()
Dim qry As String
Try
cn.Open()
qry = "select (title,imageurl) from [UploadProject] where [id] = '" & lblimageid.Text & "'"
cmnd = New SqlCommand(qry, cn)
sdr = cmnd.ExecuteReader
While (sdr.Read())
lbltitle.Text = sdr.GetValue(0).ToString
Image2.ImageUrl = sdr.GetValue(1).ToString
End While
cn.Close()
Catch ex As Exception
lblmes2.ForeColor = Drawing.Color.Red
lblmes2.Text = ex.Message
Finally
cn.Close()
End Try
End Sub
Public Sub get_Image()
Dim qry As String
Try
cn.Open()
qry = "select title,imageurl from UploadProject where id = " & lblimageid.Text
cmnd = New SqlCommand(qry, cn)
sdr = cmnd.ExecuteReader
While (sdr.Read())
lbltitle.Text = sdr.GetValue(0).ToString
Image2.ImageUrl = sdr.GetValue(1).ToString
End While
cn.Close()
Catch ex As Exception
lblmes1.ForeColor = Drawing.Color.Red
lblmes1.Text = ex.Message
Finally
cn.Close()
End Try
End Sub
Public Sub getProjectDT()
Dim qry As String
Try
qry = "select id,title,date from UploadProject "
sda = New SqlDataAdapter(qry, cn)
ds = New DataSet
sda.Fill(ds, "UploadProject")
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
Catch ex As Exception
Finally
cn.Close()
End Try
End Sub
Hi I got an InvalidCastException saying that "Specified cast is not valid.". I dont know where is the problem. Does my code has an error?
This is my code:
Private Sub Form5_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\patientinfo.accdb"
Conn.Open()
'====retrieve values in database=============
Dim statement As String = " SELECT patient_name,patient_age,date_confinement,type_sickness, type_fluid, bottle_used, drop_rate FROM tblPatientInfo WHERE 1 ORDER BY ID "
RetrieveInfos(statement)
End Sub
Public Sub RetrieveInfos(ByRef statement As String)
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = statement
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
'--read records in access database----------------
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
lblName.Text = reader.GetString(0)
lblAge.Text = reader.GetString(1)
lblDate.Text = reader.GetString(2)
lblSickness.Text = reader.GetString(3)
lblFluid.Text = reader.GetString(4)
lblBottle.Text = reader.GetString(5)
lbldrops.Text = reader.GetString(6)
reader.Close()
End If
End With
End Sub
Any help would be appreciated. Thanks! :3
A very annoying part of VB working with datatypes is that some of them cause it to have a huge flap if they're empty. Best way around is to convert the ready to either an empty value or the default null value for the data type. Try the following:
lblName.Text = If(reader.isdbnull(0),Nothing,reader.GetString(0))
lblAge.Text = If(reader.isdbnull(1), 0, reader.GetInt16(1))
lblDate.Text = If(reader.isdbnull(2), date.minvalue, reader.Getdatetime(2)
lblSickness.Text = If(reader.isdbnull(3), Nothing, reader.GetString(3)
lblFluid.Text = If(reader.isdbnull(4), Nothing, reader.GetString(4))
lblBottle.Text = If(reader.isdbnull(5), Nothing, reader.GetString(5))
lbldrops.Text = If(reader.isdbnull(6), Nothing, reader.GetString(6))
Based on your comment to the question, I would suggest changing
lblAge.Text = reader.GetString(1)
to
lblAge.Text = reader.GetInt32(1).ToString
Also, make sure you use the appropriate Get for each column. For a Date you should use GetDateTime(). Here is a link to the MSDN for OleDbDataReader; the left side will have a list of all the methods that you can use for reference.
Try checking if the value is null:
If TypeOf reader(1) Is DBNull Then
lblAge.Text = reader.GetString(1)
End If
But that will only work if it's a string. If it's not a string, this should work with any data type:
If TypeOf reader(1) Is DBNull Then
lblAge.Text = reader(1).ToString()
End If