How can I change this code to SqlConnection? - vb.net

Can anyone change this code to SqlConnection?
Dim Db As ADODB.Connection
Dim rs As ADODB.Recordset
Set Db = New ADODB.Connection
Db.ConnectionString = GetConnectString & AppPath & "schedule.mdb"
Call Db.Open
Set rs = New ADODB.Recordset
Set rs = Db.Execute("select * from tbl_Schedule where StartDate = #1/1/2002#")
While Not rs.EOF
Call Me.Schedule1.ScheduleItems.Add("", #1/1/2002#, rs!StartTime, _
rs!Length, rs!Description, "")
Call rs.MoveNext
Wend

Please find the below snippet which will helps you to get data from sql database. You can alter the script with your values. Import System.Data.SqlClient namespace to work with SqlConnection
Dim connection As New SqlConnection("Server=.\sqlexpress;Integrated security=sspi;database=Automation")
Dim query As String = "Select * from Heads"
If connection.State = ConnectionState.Closed Then connection.Open()
Using cmd As New SqlCommand(query, connection)
Dim reader As SqlDataReader = cmd.ExecuteReader
While reader.Read
ListBox1.Items.Add(reader("HeadName").ToString)
End While
reader.Close()
connection.Close()
End Using

Related

Retreiving Sharepoint List Data using vb.net

I want to retrieve SharePoint list data using VB.NET.
Below Code is for reference:-
Public Const roleGuid As String = "{8405ef03-40fl-4fan-8dl2-cf7kll1b8c1e}"
Public Const sharepointSite As String = "https://mysharepointsite.com/sites/resourceview.aspx"
Public Function getSharepointList()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConn As String
Dim sSql As String
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=1;RetrieveIds=Yes;" & _
"DATABASE=" & sharepointSite & ";" & _
"LIST=" & roleGuid & ";"
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
With cn
.ConnectionString = sConn
.Open
End With
sSql = "SELECT * FROM [Student list] as [Student List];"
rs.Open sSql, cn, adOpenStatic, adLockOptimistic
ThisWorkbook.Worksheets("Sheet1").Range("A2").CopyFromRecordset rs
End Function
Below is error screenshot that gets popup
Any method or suggestion would be helpful.
I have found out a way to retrieve data from SharePoint list using vb.net
Public Function retrieveData()
'ADD FOLLOWING REFERENCES:-
'Microsoft ActiveX Data Objects 2.8 Library
'DECLARING CONNECTION AND RECORDSET OBJECTS, SQLQUERY STRING VARIABLE.
Dim cnt As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sqlQuery As String
'SETTING UP CONNECTION AND RECORDSET OBJECTS.
cnt = New ADODB.Connection
rs = New ADODB.Recordset
'HERE STUDENT LIST IS YOUR SHAREPOINT LIST NAME.
sqlQuery = "Select * from [Student List];"
'SETTING CONNECTION STRING TO CONNECTION OBJECT AND OPENING CONNECTION.
With cnt
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=2;RetrieveIds=Yes;DATABASE=https://mysharepointlist.com/sites/;LIST={Your List GUID};"
.Open()
End With
'OPENING RECORDSET.
rs.Open(sqlQuery, cnt, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly)
'FILLING DATATABLE WITH THE HELP OF DATA ADAPTER.
Dim myDa As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter
Dim myDs As DataTable = New DataTable
myDa.Fill(myDs, rs)
'FILLING DATAGRIDVIEW WITH DATATABLE AS DATASOURCE.
DataGridView1.Datasource = myDs
'CHECKS IF CONNECTION OBJECTS AND RECORDSET OBJECT IS IN OPEN STATE IF YES THEN IT WILL CLOSE AND DEREFERENCE THEM.
If CBool(rs.State And ADODB.ObjectStateEnum.adStateOpen) = True Then rs.Close()
rs = Nothing
If CBool(cnt.State And ADODB.ObjectStateEnum.adStateOpen) = True Then cnt.Close()
cnt = Nothing
End Function

Match file in database

I have a problem where I can't get a 'msg box' that tells me files that I have browsed match with files in the database. I use an SQL Server database and I have already inserted data that matches with the files that I am browsing. This is my code:
Private Sub CmdUp_Click()
db
End Sub
Public Sub db()
Dim DBCon As ADODB.Connection
Dim Cmd As ADODB.Command
Dim Rs As ADODB.Recordset
Dim strName As String
Dim file As String
file = Text1.Text
Set DBCon = New ADODB.Connection
DBCon.CursorLocation = adUseClient
DBCon.Open "Driver={MySQL ODBC 3.51 Driver};Server=localhost;Port=3306;Database=mforce; User=root;Password=;Option=3;"
Set Cmd = New ADODB.Command
Cmd.ActiveConnection = DBCon
Cmd.CommandType = adCmdText
Cmd.CommandText = "SELECT Sample FROM static WHERE ID = 1"
Set Rs = Cmd.Execute
Do While Not Rs.EOF
Rs.MoveNext
Loop
If Form1.Text1.Text = strName Then
MsgBox " sample match"
End If
DBCon.Close
'Delete all references
Set Rs = Nothing
Set Cmd = Nothing
Set DBCon = Nothing
End Sub

Condition or Rule when Importing Excel data to SQL

At line 4 of my code, how or is it possible to have a condition in there?
For example:
Dim expr As String = "SELECT * FROM [Sheet1$] WHERE excelColumn1 <> NULL"
I have tried it, but it gives an Error: No value given for one or more required parameters.
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\z.fontanilla\Documents\etl2.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=cyayay\sqlexpress;Initial Catalog=reportingDB;Integrated Security=True"
SQLconn.ConnectionString = ConnString
SQLconn.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLconn)
bulkCopy.DestinationTableName = "tFalse"
Try
objDR = objCmdSelect.ExecuteReader
bulkCopy.BatchSize = 5000
bulkCopy.WriteToServer(objDR)
objDR.Close()
SQLconn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
ExcelConnection.Close()

Displaying data in Gridview in VB

I want to display data from database in DataGridView...This is my code...Its not working...Can anyone help me wat to do......
Dim DBCONSRT, QRYSTR As String
Dim strSQL, skunbr As String
Dim DBCON, myConn, myCommand, rs As Object
Dim NoOfRecords As Long
skunbr = TextBox1.Text
rs = CreateObject("ADODB.Recordset")
Const DB_CONNECT_STRING = "Provider=MSDASQL.1;Persist Security Info=False;User ID=cpa5k;Data Source=NP1;DSN=NP1;UID=user;PASSWORD=pass;SDSN=Default;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;Initial Catalog=QA1MM;"
myConn = CreateObject("ADODB.Connection")
myCommand = CreateObject("ADODB.Command")
myConn.Open(DB_CONNECT_STRING)
myCommand.ActiveConnection = myConn
myCommand.CommandText = "update QA1MM.STRSK_OH set OH_QTY = 250 where SKU_NBR = 100013 and STR_NBR = 116;"
myCommand.Execute()
strSQL = "select * from QA1MM.STRSK_OH where SKU_NBR = " & skunbr & " with ur FETCH FIRST 10 ROWS ONLY;"
rs.Open(strSQL, myConn)
DataGridView1.DataSource = rs
DataGridView1.Refresh()
myConn.Close()
Instead of assigning a ADODB.RecordSet directly to the datasource of datagridview like that, first convert/fill the recordset values to a dataset like below
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter
Dim myDS As DataSet = New DataSet
myDA.Fill(myDS, rs, "MyTable")
DataGridView1.DataSource = myDS.Tables(0)
DataGridView1.Refresh()
This is the classic VB way. Not .net
Please refer this MSDN link

Using SQLDataReader instead of recordset

I am new to this and had this question. Can I use SQLDataReader instead of a Recordset. I want to achieve the following result in an SQLDataReader.
Dim dbConn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sqlstr As String = "SELECT Name,Status FROM table1 WHERE id=" + item_id.Value.ToString
rs.Open(SQL, dbConn)
While Not rs.EOF
txtName.Text = rs.Fields.Item("Name").Value
ddlstatus.SelectedIndex = 1
rs.MoveNext()
End While
rs.Close()
rs = Nothing
dbConn.Close()
dbConn = Nothing
Can I replace recordset with SQLDataReader and if I can can you please show me the changes in code?
Its highly recommend that you use the using pattern:
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Using Con As New SqlConnection(sConnection)
Con.Open()
Using Com As New SqlCommand("Select * From tablename", Con)
Using RDR = Com.ExecuteReader()
If RDR.HasRows Then
Do While RDR.Read
txtName.Text = RDR.Item("Name").ToString()
Loop
End If
End Using
End Using
Con.Close()
End Using
You will have to swap out a few things, something similar to the following.
Here is an example, you will need to modify this to meet your goal, but this shows the difference.
I also recommend using a "Using" statement to manage the connection/reader. Also, a parameterized query.
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Dim objCommand As New SqlCommand
objCommand.CommandText = "Select * From tablename"
objCommand.Connection = New SqlConnection(sConnection)
objCommand.Connection.Open()
Dim objDataReader As SqlDataReader = objCommand.ExecuteReader()
If objDataReader.HasRows Then
Do While objDataReader.Read()
Console.WriteLine(" Your name is: " & Convert.ToString(objDataReader(0)))
Loop
Else
Console.WriteLine("No rows returned.")
End If
objDataReader.Close()
objCommand.Dispose()
Dim rdrDataReader As SqlClient.SqlDataReader
Dim cmdCommand As SqlClient.SqlCommand
Dim dtsData As New DataSet
Dim dtbTable As New DataTable
Dim i As Integer
Dim SQLStatement as String
msqlConnection.Open()
cmdCommand = New SqlClient.SqlCommand(SQLStatement, msqlConnection)
rdrDataReader = cmdCommand.ExecuteReader()
For i = 0 To (rdrDataReader.FieldCount - 1)
dtbTable.Columns.Add(rdrDataReader.GetName(i), rdrDataReader.GetFieldType(i))
Next
dtbTable.BeginLoadData()
Dim values(rdrDataReader.FieldCount - 1) As Object
While rdrDataReader.Read
rdrDataReader.GetValues(values)
dtbTable.LoadDataRow(values, True)
End While
dtbTable.EndLoadData()
dtsData.Tables.Add(dtbTable)
msqlConnection.Close()
Return dtsData