executing sql command from vb.net - sql

This is my code in VB.Net. I am doing connectivity from vb10 to oracle 10g. Ghe problem is my code is working fine in sql prompt as
SQL> insert into product values(pid_inc(),'name',' desc ',101,'"c:\imgloc','brand ',1,10)
but when I try to access it from vb it stops working. Why is that?
My vb code is:
Dim con As New OleDb.OleDbConnection("Provider=MSDAORA.1;User ID=jon;password=snow;Data Source=KAUSTUBH-PC;Persist Security Info=False")
con.Open()
name = TextBox1.Text
desc = TextBox2.Text
price = Val(TextBox3.Text)
available = Val(TextBox4.Text)
brand = TextBox5.Text
cat = ComboBox1.Text
If (name <> "") Then
nameflg = True
Else
nameflg = False
MsgBox(" product name cannot be empty")
End If
If (available > 0) Then
availableflg = True
Else
availableflg = False
MsgBox("quantity cannot be 0")
End If
If (brand <> "") Then
brandflg = True
Else
brandflg = False
MsgBox(" insert brand name")
End If
If (cat <> "") Then
catflg = True
Else
catflg = False
MsgBox("pleaese select categoty")
End If
If (nameflg And logoflg And brandflg And catflg And availableflg) Then
query = "Select cat_id from category where cat_name='" + cat + "'"
Dim cmd As New OleDb.OleDbCommand(query, con)
x = cmd.ExecuteScalar().ToString
cat_id = Val(x)
query = "insert into product values(pid_inc(),'" & name & "','" & desc & "'," & price & ",'" & imgloc & "','" & brand & "'," & cat_id & "," & available & ")"
Dim cmd1 As New OleDb.OleDbCommand(query, con)
cat_id = cmd1.ExecuteNonQuery()
If (cat_id = 0) Then
MsgBox("Record not inserted properly ....try again")
Else
MsgBox("Record inserted successfully")
End If
'Else
' MsgBox("please fill the fields properly")
End If
End Sub

Related

In VB.net, using OLEDB, in one execution, how do I UPDATE a column value that is also referenced in 'GROUP BY ... HAVING COUNT(*) ...' query?

I thought this would be simple task.
I was wrong!
The record with Name'A' and Number'2' needs to have it's Number changed to '0'.
Likewise with the records of Name'B', Number'1' and Name'B', Number'2'.
Why do I get "Syntax error in UPDATE statement."?
What am I missing?
Your generous help will be greatly appreciated!
My Code:
Imports System.Data.OleDb
Public Class Form1
Private sNameColumn As String = "Name"
Private sNumberColumn As String = "Number"
Private sFlagColumn As String = "Flag"
Private sOutputFormat As String = "'{0,-20} {1,10} {2,10} {3,10}"
Private Sub Form1_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
Dim oledbMyConn As New OleDb.OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0;" &
"Data Source = C:\0\NameAndNumber.mdb;" &
"Persist Security Info=True;" &
"Jet OLEDB:" &
"Database Password=123"
)
oledbMyConn.Open()
Dim sTableName As String = "NameAndNumber"
Dim sGroupQuery As String = " GROUP BY " & sNameColumn & ", " & sNumberColumn & " HAVING COUNT(*) = 1"
Dim sMyQuery As String = ""
Dim ds As DataSet = Nothing
Dim da As OleDbDataAdapter = Nothing
sMyQuery =
"SELECT * FROM " & sTableName
Debug.Print("'============================================ look at the table")
Debug.Print("'Query: " & sMyQuery)
ds = New DataSet(sTableName)
da = New OleDbDataAdapter(sMyQuery, oledbMyConn)
Try
da.Fill(ds, sTableName)
ShowResults("Table contents", ds)
Catch ex As Exception
Debug.Print("'Exception message: " & ex.Message)
End Try
sMyQuery =
"SELECT" &
" " & sNameColumn & ", " & sNumberColumn &
" FROM " & sTableName &
sGroupQuery
Debug.Print("'============================================ see if any records qualify")
Debug.Print("'Query: " & sMyQuery)
ds = New DataSet(sTableName)
da = New OleDbDataAdapter(sMyQuery, oledbMyConn)
Try
da.Fill(ds, sTableName)
ShowResults("Qualifying records", ds)
Catch ex As Exception
Debug.Print("'" & ex.Message)
End Try
Dim sMyUpdate As String =
"UPDATE " & sTableName &
" SET" &
" " & sNumberColumn & " = '0'," &
" " & sFlagColumn & " = 'P'" &
sGroupQuery
Debug.Print("'============================================ try to update the qualifying records")
Debug.Print("'Update command: " & sMyUpdate)
Dim com As OleDbCommand = New OleDbCommand
With com
.Connection = oledbMyConn
.CommandText = sMyUpdate
Try
.ExecuteNonQuery()
Catch ex As Exception
Debug.Print("'Exception message: " & ex.Message)
End Try
End With
sMyQuery =
"SELECT * FROM " & sTableName
Debug.Print("'============================================ look at the table again")
Debug.Print("'Query: " & sMyQuery)
ds = New DataSet(sTableName)
da = New OleDbDataAdapter(sMyQuery, oledbMyConn)
Try
da.Fill(ds, sTableName)
ShowResults("Table contents", ds)
Catch ex As Exception
Debug.Print("'Exception message: " & ex.Message)
End Try
End Sub
Private Sub ShowResults(ByVal sTitle As String, ByRef ds As DataSet)
Dim sCol0Val As String = ""
Dim sCol1Val As String = ""
Dim sCol2Val As String = ""
With ds
If .Tables IsNot Nothing AndAlso .Tables.Count > 0 Then
Debug.Print(String.Format(sOutputFormat, sTitle, sNameColumn, sNumberColumn, sFlagColumn))
With .Tables(0)
For r As Integer = 0 To .Rows.Count - 1
sCol0Val = ""
sCol1Val = ""
sCol2Val = ""
Try
sCol0Val = .Rows(r).Item(0)
sCol1Val = .Rows(r).Item(1)
sCol2Val = .Rows(r).Item(2)
Catch
End Try
Debug.Print(
String.Format(
sOutputFormat,
"Record # " & r.ToString,
sCol0Val,
sCol1Val,
sCol2Val
)
)
Next
End With
End If
End With
End Sub
End Class
The Debug.Prints:
'============================================ look at the table
'Query: SELECT * FROM NameAndNumber
'Table contents Name Number Flag
'Record # 0 A 1
'Record # 1 A 1
'Record # 2 A 2
'Record # 3 B 1
'Record # 4 B 2
'Record # 5 B 3
'Record # 6 B 3
'============================================ see if any records qualify
'Query: SELECT Name, Number FROM NameAndNumber GROUP BY Name, Number HAVING COUNT(*) = 1
'Qualifying records Name Number Flag
'Record # 0 A 2
'Record # 1 B 1
'Record # 2 B 2
'============================================ try to update the qualifying records
'Update command: UPDATE NameAndNumber SET Number = '0', Flag = 'P' GROUP BY Name, Number HAVING COUNT(*) = 1
'Exception message: Syntax error in UPDATE statement.
'============================================ look at the table again
'Query: SELECT * FROM NameAndNumber
'Table contents Name Number Flag
'Record # 0 A 1
'Record # 1 A 1
'Record # 2 A 2
'Record # 3 B 1
'Record # 4 B 2
'Record # 5 B 3
'Record # 6 B 3
Thank you jmcilhinney for your response.
It became obvious that iteration based on the 'GROUP BY' results was the only way to achieve what I want.
Also, the SET command needed to have the Number column bracketed. Found that through trial and error testing.
The 'GROUP BY' code, then the iteration based on that result, then the updated table:
sMyQuery =
"SELECT" &
" " & sNameColumn & ", " & sNumberColumn &
" FROM " & sTableName &
sGroupQuery
Debug.Print("'============================================ see if any records qualify")
Debug.Print("'Query: " & sMyQuery)
ds = New DataSet(sTableName)
da = New OleDbDataAdapter(sMyQuery, oledbMyConn)
Try
da.Fill(ds, sTableName)
ShowResults("Qualifying records", ds)
Catch ex As Exception
Debug.Print("'" & ex.Message)
End Try
Dim sMyUpdate As String = ""
Dim com As OleDbCommand = New OleDbCommand
With com
.Connection = oledbMyConn
With ds.Tables(0)
For Each r As DataRow In .Rows
sMyUpdate =
"UPDATE " & sTableName &
" SET" &
" [" & sNumberColumn & "] = '0', " & sFlagColumn & " = 'P'" &
" WHERE " &
sNameColumn & " = '" & r.Item(sNameColumn).ToString & "'" &
" AND " &
sNumberColumn & " = '" & r.Item(sNumberColumn).ToString & "'"
com.CommandText = sMyUpdate
Try
com.ExecuteNonQuery()
Catch ex As Exception
Debug.Print("'Exception message: " & ex.Message)
End Try
Next
End With
End With
'============================================ look at the table again
'Query: SELECT * FROM NameAndNumber
'Table contents Name Number Flag
'Record # 0 A 1
'Record # 1 A 1
'Record # 2 A 0 P
'Record # 3 B 0 P
'Record # 4 B 0 P
'Record # 5 B 3
'Record # 6 B 3

Join Three Table in QODBC

I didn't get any error but there is no data that is displaying in the datagridview . Is there anything that i should add in my codes ? so it will display the data that i need ?
If MSG = vbYes Then
Timer1.Enabled = True
Me.stpLoadBar.Value = 0
Me.stpLoadBar.Value = increment
'Me.lstSearch.Items.Clear()
If Me.txtRefFR.Text = "" Or Me.txtRefTO.Text = "" Then
MessageBox.Show("Check Number is required and must not be blank.")
'Me.cmdPrint.Enabled = False
ElseIf CInt(Me.txtRefFR.Text) > CInt(Me.txtRefTO.Text) Then
MessageBox.Show("Check Number From must not be greater than Check Number To.")
Me.txtRefFR.Text = ""
Me.txtRefTO.Text = ""
Else
If Me.chkEnterBill.Checked = True Then
strSelect = "SELECT billpaymentcheckline.Txnnumber, billpaymentcheckline.payeeentityreffullname, billpaymentcheckline.txndate, billpaymentcheckline.bankaccountreffullname , billexpenseline.memo " _
& ", billpaymentcheckline.amount, billpaymentcheckline.refnumber, billpaymentcheckline.appliedtotxnrefnumber, billpaymentcheckline.appliedtotxntxndate, billpaymentcheckline.appliedtotxnamount from billpaymentcheckline INNER JOIN BillExpenseLine ON (billpaymentcheckline.appliedtotxnrefnumber = billexpenseline.refnumber) WHERE" _
& " billpaymentcheckline.refnumber BETWEEN '" & CInt(Me.txtRefFR.Text) & "' AND '" & CInt(Me.txtRefTO.Text) & "' AND" _
& " billpaymentcheckline.bankaccountreffullname='" & Me.lblBankName.Text & "'ORDER BY billpaymentcheckline.refnumber"
Try
Dim conChk As New Odbc.OdbcConnection(My.Settings.strConn)
conChk.Open()
Dim cmdChk As New Odbc.OdbcCommand(strSelect, conChk)
cmdChk.CommandType = CommandType.Text
Dim daChk As New Odbc.OdbcDataAdapter(cmdChk)
daChk.Fill(dsCVI, "tblvoucheritem")
With dgvCV
.RowsDefaultCellStyle.BackColor = Color.White
.AlternatingRowsDefaultCellStyle.BackColor = Color.DeepSkyBlue
.DataSource = dsCVI.Tables("tblvoucheritem")
.ReadOnly = True
End With
daChk.Dispose()
cmdChk.Dispose()
conChk.Close()
Me.rbCheck.Enabled = True
Me.rbCV.Enabled = True
Catch ex As Exception
MessageBox.Show(ex.Message)
Me.rbCheck.Enabled = False
Me.rbCV.Enabled = False
Finally
End Try
Me.stpLoadBar.Value = 100

Data inserted from datagridview not updated in SQL Server

I'm still adjusting to the vb.net environment so I want to ask a question..
I have my code here:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim connstr As String = "server=supertelco\sqlexpress; database=testdb; user= sa; password=sa;"
cmdconn = New SqlConnection
cmd = New SqlCommand
cmdconn.ConnectionString = connstr 'sqlstr
cmd.Connection = cmdconn
cmdconn.Open()
Dim period, VOUCH_AMT, INDIVIDUAL_AMT, check_no, D_MAILED, DIR_NO, who_updated As String
For i As Integer = 0 To Me.DataGridView2.Rows.Count - 1
With Me.DataGridView2.Rows(i)
If IsDBNull(.Cells(0).Value()) OrElse .Cells(0).Value() Is Nothing OrElse .Cells(0).Value().ToString().Trim() = "" Then
period = ""
Else
period = .Cells(0).Value()
End If
If IsDBNull(.Cells(1).Value()) OrElse .Cells(1).Value() Is Nothing OrElse .Cells(1).Value().ToString().Trim() = "" Then
VOUCH_AMT = "0"
Else
VOUCH_AMT = .Cells(1).Value()
End If
If IsDBNull(.Cells(2).Value()) OrElse .Cells(2).Value() Is Nothing OrElse .Cells(2).Value().ToString().Trim() = "" Then
INDIVIDUAL_AMT = "0"
Else
INDIVIDUAL_AMT = .Cells(2).Value()
End If
If IsDBNull(.Cells(3).Value()) OrElse .Cells(3).Value() Is Nothing OrElse .Cells(3).Value().ToString().Trim() = "" Then
check_no = ""
Else
check_no = .Cells(3).Value()
End If
If IsDBNull(.Cells(4).Value()) OrElse .Cells(4).Value() Is Nothing OrElse .Cells(4).Value().ToString().Trim() = "" Then
D_MAILED = ""
Else
D_MAILED = .Cells(4).Value()
End If
If IsDBNull(.Cells(5).Value()) OrElse .Cells(5).Value() Is Nothing OrElse .Cells(5).Value().ToString().Trim() = "" Then
DIR_NO = ""
Else
DIR_NO = .Cells(5).Value()
End If
If IsDBNull(.Cells(6).Value()) OrElse .Cells(6).Value() Is Nothing OrElse .Cells(6).Value().ToString().Trim() = "" Then
who_updated = ""
Else
who_updated = .Cells(6).Value()
End If
End With
cmd.CommandText = "insert into tobee.EBD_BILLHISTORY(period, vouch_amt, individual_amt, check_no, d_mailed, dir_no, who_updated)values" & _
"('" & period.Replace("'", "''") & "'," & VOUCH_AMT & "," & INDIVIDUAL_AMT & ",'" & check_no.Replace("'", "''") & "','" & D_MAILED.Replace("'", "''") & "', '" & DIR_NO.Replace("'", "''") & "','" & who_updated.Replace("'", "''") & "')"
cmd.ExecuteNonQuery()
MsgBox("Saved")
Next
cmdconn.Close()
End Sub
so yeah, all code works fine except the updates in SQL Server. I wonder why the changes I made in dgv was not being reflected in the database after clicking the save button? Could someone help me about this? Am I missing something?
I would suggest to copy the value cmd.CommandText has before you call ExecuteNonQuery to the clipboard and execute it in Sql Server Management Studio ... and see what happens (error messages) ... apart from this you should think about using SqlParameters ...

vb.net Read and write data to ms database using Odbc(ERROR)

When I try to run the program, an error shows " ERROR[07002][Microsoft][ODBC MICROSOFT ACCESS DRIVER] TOO FEW PARAMETERS.EXPECTED 1" USING THIS CONNECTION.
Public Sub open_connection ()
Try
con = New OdbcConnection("dsn = LocalDB")
con.Open()
End try
Catch ex As Exception
MsgBox(ex.message)
End sub
Problems occurs when inserting and reading..
sSql = "select * from Faculty where RFID='" & txtrfid.Text & "'"
Dim cmd As New OdbcCommand(sSql, con)
Dim dr As OdbcDataReader = cmd.ExecuteReader()
If dr.HasRows Then
dr.Read()
txtfname.Text = dr("fname").ToString()
txtlname.Text = dr("lname").ToString()
txtid.Text = dr("STID").ToString()
txtposition.Text = dr("Pstion").ToString()
txtsubject.Text = dr("Subject").ToString()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
dr.Close()
sSql = " SELECT TOP 1 flag_inout FROM Attendance where faculty_id = #StId ORDER BY Attendance_id DESC"
Dim pcmd As New OdbcCommand(sSql, con)
pcmd.Parameters.AddWithValue("#StId", txtid.Text)
Dim pdr As OdbcDataReader = pcmd.ExecuteReader()
While pdr.Read()
TextBox1.Text = pdr("flag_inout").ToString()
End While
If TextBox1.Text = "IN" Then
TextBox1.Text = "OUT"
ElseIf TextBox1.Text = "OUT" Then
TextBox1.Text = "IN"
ElseIf TextBox1.Text = Nothing Then
TextBox1.Text = "IN"
End If
pdr.Close()
'Check Duplicate
'If txtfname.Text.Length = 0 Then
' Return
'End If
'If Not CheckDateDuplicate() Then
' MessageBox.Show("Already Saved on this Date")
' Return
'End If
sSql = "insert into Attendance (faculty_id, faculty_Fname,faculty_Lname,[Position],Subject, attendance_date, attendance_time, flag_inout) values('" & txtid.Text & "','" & txtfname.Text & "','" & txtlname.Text & "','" & txtposition.Text & "','" & txtsubject.Text & "','" & DateTimePicker1.Value.Date & "','" & TimeOfDay.ToShortTimeString & "','" & TextBox1.Text & "')"
Dim xcmd As New OdbcCommand(sSql, con)
If xcmd.ExecuteNonQuery() > 0 Then
'MessageBox.Show("ATTENDANCE SAVED")
txtrfid.Text = ""
'txtid.Text = ""
'txtfname.Text = ""
'txtlname.Text = ""
'txtposition.Text = ""
'txtsubject.Text = ""
txtrfid.Focus()
Dtagrid()
End If
If TextBox1.Text = "IN" Then
lblinuse.Visible = True
lblvacant.Visible = False
lbllstuser.Visible = False
lblcrrntuser.Visible = True
ElseIf TextBox1.Text = "OUT" Then
lblinuse.Visible = False
lblvacant.Visible = True
lbllstuser.Visible = True
lblcrrntuser.Visible = False
'txtid.Text = ""
'txtfname.Text = ""
'txtlname.Text = ""
'txtposition.Text = ""
'txtsubject.Text = ""
'imgRetrieve.Image = Nothing
End If
End If
Dtagrid()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
CAUSE
This error occurs only with Microsoft Access when one of the column
names specified in a select statement does not exist in the table
being queried.
Resolution
Remove any invalid column names from the select statement.
Make sure that Column Name RFID exist in Faculty table and also check txtrfid has value or not

vbnet multiple combobox fill with one dataset

i have the following code to fill two comboboxes using one dataset:
Private Sub sub_cbo_type_load()
Dim ds As New DataSet
ds = cls.cbo_type()
If ds IsNot Nothing _
AndAlso ds.Tables.Count > 0 _
AndAlso ds.Tables(0).Rows.Count > 0 Then
Me.r_cbo_type.DataSource = ds.Tables(0)
Me.r_cbo_type.DisplayMember = "desc"
Me.r_cbo_type.ValueMember = "code"
Me.r_cbo_type.SelectedIndex = -1
Me.m_cbo_type.DataSource = ds.Tables(0)
Me.m_cbo_type.DisplayMember = "desc"
Me.m_cbo_type.ValueMember = "code"
Me.m_cbo_type.SelectedIndex = -1
End If
End Sub
the problems is: whenever the index is changed in one combobox, it's automatically changed in the other one too.
does anyone know how can i solve this?
thanks for your time.
Try cloning the tables:
Private Function CopyTable(ByVal sourceTable As DataTable) As DataTable
Dim newTable As DataTable = sourceTable.Clone
For Each row As DataRow In sourceTable.Rows
newTable.ImportRow(row)
Next
Return newTable
End Function
Then your data sources would be referencing different sources:
Me.r_cbo_type.DataSource = CopyTable(ds.Tables(0))
Me.m_cbo_type.DataSource = CopyTable(ds.Tables(0))
do like this
Private Sub btn_update1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_update1.Click
If MsgBox("Are you sure to update?" & "", MsgBoxStyle.YesNo, "Confirmation") = MsgBoxResult.Yes = True Then
Dim transmode As String = vbNullString
Dim byair As String = vbNullString
Dim bysea As String = vbNullString
If rb_air.Checked = True Then
transmode = "A"
byair = txt_mserial.Text '.Substring(txt_mserial.TextLength - 4, 4)
bysea = vbNullString
ElseIf rb_sea.Checked = True Then
transmode = "B"
byair = vbNullString
bysea = txt_mserial.Text '.Substring(txt_mserial.TextLength - 4, 4)
End If
Try
If con.State = ConnectionState.Closed Then con.Open()
global_command = New SqlCommand("update ytmi_finished_products set rev_ctrl_no = '" & txt_mrev.Text & "', by_air = '" & byair & "', by_sea = '" & bysea & "', transport_mode = '" & transmode & "' where REPLACE(prod_no, '-', '') +'-'+ ISNULL(CONVERT(varchar(50), prod_sx), '') + prod_lvl = '" & txt_mpart.Text & "' and cast(serial_no as numeric) = '" & txt_mserial.Text & "' and req_box_qty = '" & txt_mqty.Text & "' and remarks is null", con)
global_command.ExecuteNonQuery()
global_command.Dispose()
MsgBox("Successfully Updated!", MsgBoxStyle.Information, "Message")
mclear()
Catch ex As Exception
MsgBox("Trace No 20: System Error or Data Error!" + Chr(13) + ex.Message + Chr(13) + "Please Contact Your System Administrator!", vbInformation, "Message")
End Try
End If
End Sub