SqlDataAdapter not filling data table with SQL Where Clause - sql-server

Attempting to fill a data table using SqlDataAdapter with a WHERE clause but it returns nothing. The SQL command itself returns data from SSMS and removing just the WHERE clause in code fills data table as expected.
Dim adapter As New SqlDataAdapter
Dim datatable As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
adapter = New SqlDataAdapter("SELECT * FROM [MyProjectDtbl] WHERE zipcode = 22021", cnn)
adapter.Fill(datatable)
adapter.Dispose()
End Using
Digging through the Select command EventSink, I found:
Unable to cast object of type 'System.Data.SqlClient.SqlInternalConnectionTds' to type 'System.Data.SqlClient.SqlInternalConnectionSmi'

Try it with parameters.
Private Sub OPCode()
Dim dt As New DataTable
Using cnn As New SqlConnection(connectionString),
cmd As New SqlCommand("SELECT * FROM [MyProjectDtbl] WHERE zipcode = #zip", cnn)
cmd.Parameters.Add("#zip", SqlDbType.Int).Value = 22021
cnn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Debug.Print(dt.Rows.Count.ToString)
End Sub

Related

Datagridview only shows the row but no the data

I'm using datetimepicker to choose the date to show the data from the microsoft sql server but the cells are empty.
I use LIKE operator to show the purchased item within the day.
This is the code:
Public Sub see4()
'MYPOPUL4TE D4T4GRIDVIEW3
Dim query As String = "SELECT * FROM projectsd.dbo.cart WHERE dates LIKE '" & DateTimePicker1.Text & "'"
Using cmd As SqlCommand = New SqlCommand(query, con)
Using da As New SqlDataAdapter
da.SelectCommand = cmd
Using dt As New DataTable()
da.Fill(dt)
DataGridView3.DataSource = dt
End Using
End Using
End Using
End Sub

vb write information from SQL Server database

I use visual basic 2008 and a SQL Server database. I want to write the information stock in the database and I want to be rank like in php I use table to rank information what the method to do that in vb. This code write only last information into the table tbl_cars
Dim da As SqlDataAdapter
Dim dt As DataTable
Dim sqlconn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\m7md\Documents\Visual Studio 2008\Projects\Cars\Cars\cars.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
dt = New DataTable
da = New SqlDataAdapter
Dim sql As String = ("select * from tbl_cars ")
da = New SqlDataAdapter(sql, sqlconn)
sqlconn.Open()
da.Fill(dt)
For Each drRow As DataRow In dt.Rows
Label6.Text= (drRow.Item("db_type").ToString)
Label7.Text = (drRow.Item("db_gender").ToString)
Label8.Text = (drRow.Item("db_color").ToString)
Label9.Text = (drRow.Item("db_price").ToString)
Next
End Sub

VB.Net -- Bulk Insert XML into Existing SQL Server Table

I recently figured out how to export data as XML from SQL Server using VB.Net. I use three SQL statements and dimension an XPath document to add the root tags to the export:
Dim connectionString As String
Dim connection As New SqlConnection
Dim command As New SqlCommand()
Dim sql = "select * from scheduledata for xml auto, elements " & _
"select * from costdata for xml auto, elements " & _
"select * from csintegrationdata for xml auto, elements "
connectionString = "Data Source=(localdb)\v11.0; _
Initial Catalog=localACETest;Integrated Security=True"
connection = New SqlConnection(connectionString)
connection.Open()
command.CommandText = sql
command.Connection = connection
command.CommandType = CommandType.Text
Dim xmlRead As XmlReader = command.ExecuteXmlReader()
Dim xp As New XPath.XPathDocument(xmlRead)
Dim xn As XPath.XPathNavigator = xp.CreateNavigator()
Dim xd As New XmlDocument
Dim root As XmlNode = xd.CreateElement("Data")
root.InnerXml = xn.OuterXml
xd.AppendChild(root)
Dim fStream As New FileStream(Directory, FileMode.Create, FileAccess.ReadWrite)
xd.Save(fStream)
fStream.Close()
I would like to be able to re-import this data into the SQL tables using VB, but I'm having some trouble. The code I'm using is this:
Using sqlconn As New SqlConnection(connectionString)
Dim ds As New DataSet()
Dim sourcedata As New DataTable()
Dim ii As Integer = 0
ds.ReadXml("C:\Users\coopere.COOPERE-PC\Desktop\Test.xml")
sqlconn.Open()
Using bulkcopy As New SqlBulkCopy(sqlconn)
sourcedata = ds.Tables(0)
bulkcopy.DestinationTableName = "CSIntegrationData"
bulkcopy.ColumnMappings.Add("Period", "Period")
bulkcopy.ColumnMappings.Add("Program", "Program")
bulkcopy.ColumnMappings.Add("CostControlAccount", "CostControlAccount")
...
bulkcopy.WriteToServer(sourcedata)
End Using
sqlconn.Close()
End Using
When doing this, I get an error: System.InvalidOperationException: The given ColumnName 'CostControlAccount' does not match up with any column in data source.
I believe the reason for this is because one of the tables that exported to XML has a column full of NULL values which aren't winding up anywhere in the XML. But that won't always be the case -- oftentimes, there will be values.
Considering SqlBulkCopy's columnmappings can't handle accepting null values, how can I handle null values in my Export/Import? I'm also open to a different route entirely.
After much digging, I found this link.
As part of the FOR XML function you can tack on XSINIL at the end to handle null values. The resulting XML is below.
select * from TABLENAME for xml auto, elements XSINIL
<ScheduleWorkPackage xsi:nil="true" />

retrieving data in VB from SQL

I use Visual Basic 2010 and Microsoft SQL Server 2008. I have my database and my table and i made the connection (at least i think i did) in VB using only the interface.
What i want to know is how to get data from the database and use it into my VB project. I have of course searched for solutions already but the differences i find only confuse me more. What i need to know are the basics, the tools/objects and procedures to retrieve the data.
What i try to do at the moment is make a simple selection and put that data into a listbox right when the program starts, like this:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SqlConnection1.Open()
SqlConnection1.Close()
End Sub
End Class
1) Create your connection string
Dim connectionString As String = "Data Source=localhost;........."
2) Connect to your Database
Dim connection As New SqlConnection(connectionString)
conn.Open()
3) Create a Command and the query
Dim command As New SqlCommand("SELECT * FROM Product", connection)
Dim reader As SqlDataReader = command.ExecuteReader() //Execute the Query
4) Retrieve your result. There are several ways
Dim dt As New DataTable()
dt.Load(reader)
'Close the connection
connection.Close()
5) Bind to your list box
myListBox.ItemSource = dt
Full code here
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand("Select * from Products", connection)
command.Connection.Open()
SqlDataReader reader = command.ExecuteReader()
End Using
For more info
SQLCommand
SqlConnection1.Open()
using table As DataTable = New DataTable
using command as SqlCommand = New SqlCommand("SELECT blah blah", SqlConnection1)
using adapter As SqlDataAdapter = new SqlDataAdapter(command)
adapter.Fill(table)
end using
end using
for each row As DataRow in table.Rows
' add each listbox item
listbox1.Items.Add(row("column name"))
next
end using
SqlConnection1.Close()

VB.NET Dataset update

I'm new to vb.net and having quite a challenge with updating a field in a table using the For...Next construct on a data set. Sample code below - can anyone tell me what I'm missing? I know this particular example could be accomplished with a simple SQL update statement, but the actual use for what this code will become requires stepping through each record in the dataset. The example below is just a simple one to let me get the procedure down. Note that this runs without an exception, but just doesn't change the data in the table.
Help! :)
Dim objConn As SqlConnection = New SqlConnection("Data Source=DALLAS\;Initial Catalog=Adaptive;Integrated Security=True")
Dim selectCMD As SqlCommand = New SqlCommand("SELECT * from dwbprocref", objConn)
selectCMD.CommandTimeout = 30
Dim custDA As SqlDataAdapter = New SqlDataAdapter
custDA.SelectCommand = selectCMD
Dim custCB As SqlCommandBuilder = New SqlCommandBuilder(custDA)
custCB.QuotePrefix = "["
custCB.QuoteSuffix = "]"
Dim dRow As DataRow
Dim dTable As DataTable
objConn.Open()
Dim custDS As DataSet = New DataSet
custDA.Fill(custDS, "dwbprocref")
For Each dRow In custDS.Tables(0).Rows
If dRow.Item("pr_format") = "MDV" Then
dRow.Item("pr_tester") = "X"
End If
custDS.AcceptChanges()
Next
custDA.Update(custDS, "dwbprocref")
objConn.Close()
You're calling AcceptChanges. This marks all of the rows as being unmodified, so they are never updated in the database. Remove this call and you should be good.

Resources