myConnection.Open()
rtb_Address.Clear()
txt_Name.Clear()
Dim str As String
str = "SELECT * FROM table1 WHERE (cus_ID = '" & txt_ID.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader()
While dr.Read()
rtb_Address.Text = dr("cus_Addr").ToString
txt_Name.Text = dr("cus_Name").ToString
End While
myConnection.Close()
Error in dr = cmd.ExecuteReader()
dr is declared as OleDbDataReader
cus_ID is probaly a numeric data type, but you try to query it with a string: (cus_ID = 'thevalue').
Just remove the enclosing ': (cus_ID = thevalue)
or better, use a parameterized query to prevent sql-injection.
I would recommend the following:
Using cmd As New OleDbCommand("SELECT * FROM table1 WHERE cus_ID = #ID", con)
cmd.Parameters.AddWithValue("#ID", txt_ID.Text)
dr = cmd.ExecuteReader()
While dr.Read()
rtb_Address.Text = dr("cus_Addr").ToString
txt_Name.Text = dr("cus_Name").ToString
End While
End Using
Related
Hello i have a restaurant application i try to make a function to get transaction number for order but some times i get the same transaction number
Function GetTransNo() As String
Try
Dim sdate As String = Now.ToString("yyyyMMdd")
cn.Open()
cm = New SqlCommand("Select * From TblCart Where TransNo Like '" & sdate & "%' Order By Id Desc", cn)
dr = cm.ExecuteReader
dr.Read()
If dr.HasRows Then
GetTransNo = CLng(dr.Item("Transno").ToString) + 1
Else
GetTransNo = sdate & "0001"
End If
dr.Close()
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox(ex.Message, vbCritical)
GetTransNo = ""
End Try
Return GetTransNo
End Function
and this sub to get orders i get an empty table name and the same transaction number
Sub GetOrder()
Dim found As Boolean
Dim tno As String = ""
cn.Open()
cm = New SqlCommand("Select * From tblcart Where tableno like '" & LblTable.Text & "' and status like 'Pending'", cn)
dr = cm.ExecuteReader
dr.Read()
If dr.HasRows Then
found = True
tno = dr.Item("TransNo").ToString
Else
found = False
End If
dr.Close()
cn.Close()
If found = True Then
LblTransNo.Text = tno
loadcart()
End If
End Sub
My script does not insert any data in the database table and it does not throw any error either.
The server, database and table names are correct.
The workbook is selected using filedialog (hence correct filepath) and the worksheet name seems correct too.
I have data in column A. My table is made of 2 fields:
ID (Identity, autocrement)
CustomerName
The While Loop performs 2 iterations but I have 4 records on the worksheet.
Any idea why the data does not insert in the table?
'Open the dialog box to select the file to upload
Dim fd As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String
fd.InitialDirectory = "C:\"
fd.Filter = "Excel Files|*.xlsx"
fd.FilterIndex = 2
fd.RestoreDirectory = True
'declare variables - edit these based on your particular situation
Dim ssqltable As String = "tbl1"
Dim myexceldataquery As String = "select CustomerName from [A$]"
'create our connection strings
Dim sexcelconnectionstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFileName & ";Extended Properties=Excel 12.0;"
Dim ssqlconnectionstring As String = "Data Source=AA1\SQL001_DEV001;Initial Catalog=DB_Test;Integrated Security=True"
'execute a query to erase any previous data from our destination table
Dim sclearsql As String = Convert.ToString("delete from ") & ssqltable
Dim sqlconn As New SqlClient.SqlConnection(Connections.MyMainSQLServer)
Dim sqlcmd As New SqlCommand(sclearsql, sqlconn)
sqlconn.Open()
sqlcmd.ExecuteNonQuery()
sqlconn.Close()
'series of commands to bulk copy data from the excel file into our sql table
Dim oledbconn As New OleDbConnection(sexcelconnectionstring)
Dim oledbcmd As New OleDbCommand(myexceldataquery, oledbconn)
oledbconn.Open()
Dim dr As OleDbDataReader = oledbcmd.ExecuteReader()
Dim bulkcopy As New SqlBulkCopy(ssqlconnectionstring)
bulkcopy.DestinationTableName = ssqltable
While dr.Read()
bulkcopy.WriteToServer(dr)
End While
dr.Close()
oledbconn.Close()
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\MyExcelSpreadsheet.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=Yes""")
ExcelConnection.Open()
Dim expr As String = "SELECT * FROM [Sheet1$]"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
Dim objDR As OleDbDataReader
Dim SQLconn As New SqlConnection()
Dim ConnString As String = "Data Source=MMSQL1;Initial Catalog=DbName; User Id=UserName; Password=password;"
SQLconn.ConnectionString = ConnString
SQLconn.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLConn)
bulkCopy.DestinationTableName = "TableToWriteToInSQLSERVER"
Try
objDR = objCmdSelect.ExecuteReader
bulCopy.WriteToServer(objDR)
objDR.Close()
SQLConn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
I'm trying to populate a combobox with data from SQL Server. This is my code so far. There are asterisks around the errors. Also, ignore the comments.
Private Sub frmOriginal_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connetionString As String = Nothing
Dim sqlcon As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
Dim sql As String = Nothing
connetionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
sql = "select * from TickerSymbol"
sqlcon = New SqlConnection(connetionString)
Try
sqlcon.Open()
command = New SqlCommand(sql, sqlcon)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
sqlcon.Close()
cboID.DataSource = ds.Tables(0)
cboID.ValueMember = "TickerSymbol"
cboID.DisplayMember = "TickerSymbol"
Catch ex As Exception
'MessageBox.Show("Can not open connection ! ")'
End Try
End Sub
Private Sub cboID_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboID.SelectedIndexChanged
Dim dr As SqlDataReader
Dim command As New SqlCommand *(queryString, connection)*
Dim dataReader As SqlDataReader = command.ExecuteReader()
Dim sqlcon As SqlConnection
Dim cmd As SqlCommand
sqlcon = New SqlConnection
sqlcon.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
Try
sqlcon.Open()
cmd = New SqlCommand
cmd.CommandText = " select * from TickerSymbol where TickerSymbol = '" & cboID.Text & "'"
cmd = New SqlCommand(cmd.CommandText, sqlcon)
dr = cmd.ExecuteReader
While dr.Read()
'TxtID.Text = dr.GetInt32(0)'
'TxtSN.Text = dr.GetString(1)'
'TxtGender.Text = dr.GetString(2)'
'TxtPhone.Text = dr.GetInt32(3)'
'TxtAdrress.Text = dr.GetString(4)'
lblCompanyName.Text = dataReader.GetString(1)
lblPurchasePrice.Text = dataReader.GetSqlMoney(2)
lblQtyPurchased.Text = dataReader.GetInt32(3)
lblPurchaseDate.Text = dataReader.GetDateTime(4)
End While
sqlcon.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
sqlcon.Dispose()
End Sub
Please use parameterized queries as this will format values properly e.g. apostrophes in text will escape properly with parameters while without you must handle them, dates will be formatted properly too. Code is much cleaner also.
Example, syntax for Framework 3.5 and higher. If a connection string is used more than once then consider placing it in a private variable or under My.Settings under project properties.
Using cn As New SqlConnection With {.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"}
Using cmd As New SqlCommand With {.Connection = cn, .CommandText = "select * from TickerSymbol where TickerSymbol = #TickerSymbol"}
cmd.Parameters.AddWithValue("#TickerSymbol", cboID.Text)
cn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
'
'
'
End While
End If
End Using
End Using
I'm trying to update a database through a datagridview but the problem I'm having is that it only updates the first row in the datagridview. Any insight will be grateful, thanks.
Dim Connection As New OleDbConnection(Get_Constring)
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("ID", Type.GetType("System.Int32"))
dt.Columns.Add("Attendance", Type.GetType("System.String"))
For i = 0 To ClassRegisterdgv.Rows.Count - 1
' If ClassRegisterdgv.Rows(i).Cells(4).Value.Equals("") Then ClassRegisterdgv.Rows(i).Cells(4).Value.Equals("Present")
Dim ID As Integer = ClassRegisterdgv.Rows(i).Cells(0).Value
Dim Attendance As String = ClassRegisterdgv.Rows(i).Cells(4).Value
row = dt.Rows.Add
row.Item("ID") = ID
row.Item("Attendance") = Attendance
Next
If Connection.State = ConnectionState.Closed Then
Connection.Open()
End If
Dim sqlquery As String = "UPDATE PupilInfo SET " & NewColumnCreated & " = #Attendance WHERE ID = #ID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
'For i = 0 To ClassRegisterdgv.Rows.Count - 1
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Attendance", newrow.Item(1))
.Parameters.AddWithValue("#ID", newrow.Item(0))
.Connection = Connection
MessageBox.Show(newrow.Item(1) & newrow.Item(0))
.ExecuteNonQuery()
End With
Next
Connection.Close()
ClassRegisterdgv.DataSource = Nothing
dt.Clear()
Only updates the first row because the parameters collection of the command object has not been cleaned. Try to do the following:
With sqlcommand
.CommandText = sqlquery
.Parameters.Clear() '<─────── Insert this line in your code.
.Parameters.AddWithValue("#Attendance", newrow.Item(1))
.Parameters.AddWithValue("#ID", newrow.Item(0))
.Connection = Connection
MessageBox.Show(newrow.Item(1) & newrow.Item(0))
.ExecuteNonQuery()
End With
i want to increment a no. from sql it should be like this 13-001 but it makes 13-1 here's my code
Private Sub getLastID()
Dim dr As SqlDataReader
Dim Cmd As New SqlCommand
con.Open()
With Cmd
.Connection = con
.CommandText = "SELECT * FROM tbl_student ORDER BY Student_no DESC"
End With
dr = Cmd.ExecuteReader
If dr.Read Then
lblStudentNo.Text = Val(dr.Item(0)) + 1
End If
con.Close()
End Sub
what should i do? thank you
You can use PadLeft method.
Try this:
lblStudentNo.Text = Val(dr.Item(0)) & "-" & "1".PadLeft(3, "0")