Trying to get my head round ASP.NET DALs and TableAdapters and I'm hoping somebody can help me with getting the column data when using SQL query parameters.
If I have a TableAdapter with a query that returns one or more rows, I can get row and column data from the datatable no problem. For a simple query which returns one row I can use:
SQL: SELECT firstName, lastName from Names WHERE ID=1
Dim MyAdapter1 As New ProjectTableAdapters.NamesTableAdapter1
Dim f As String = MyAdapter1.GetNames.Rows(0)("firstName")
Dim l As String = MyAdapter1.GetNames.Rows(0)("lastName")
However if use a TableAdapter which has a query with a parameter I keep getting exceptions thrown. I'm sure this is simple, if someone can point me in right direction (vb if possible). Thanks a lot.
SQL: SELECT firstName, lastName from Names WHERE ID=#ID
Dim ID As Integer = 1
Dim MyAdapter2 As New ProjectTableAdapters.NamesTableAdapter2
Dim f As String = MyAdapter2.GetNames(Rows(0)("firstName"),ID) [throws exection]
Edit:
I think I have it working now - my bad syntax...
Dim f As String = MyAdapter2.GetNames(ID).Rows(0)("firstName")
Public Function MyFunction() As DataSet
Dim conString As String = "Connection String"
Dim conn As New SqlConnection(conString)
Dim da As New SqlDataAdapter()
Dim cmd As New SqlCommand With {
.Connection = conn,
.CommandText = "SELECT firstName, lastName from Names WHERE ID=#ID",
.CommandType = CommandType.Text}
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = 1
da.SelectCommand = cmd
Dim ds As DataSet = New DataSet()
conn.Open()
da.Fill(ds)
conn.Close()
Return ds
End Function
Related
Dim Test123 As String
Dim Conn As OleDb.OleDbConnection = New OleDbConnection("Private")
Conn.Open()
Dim mySelectQuery As String = "SELECT mti_part_no,sum(mpcs.shop_inv_history.quantity) As FebQTY from mpcs.shop_inventory, mpcs.shop_inv_history where mpcs.shop_inv_history.date_time Like '%Feb% %2015%' AND comments = 'CHECK ITEM OUT' AND mpcs.shop_inventory.si_key=mpcs.shop_inv_history.si_key AND SHOP_INVENTORY.CATEGORY BETWEEN 900 and 999 AND SHOP_INVENTORY.SCRAP_FLAG <> 1 group by mti_part_no order by FebQTY DESC"
Dim CMD As OleDbCommand = New OleDbCommand(mySelectQuery, Conn)
Dim Myreader As OleDbDataReader
Myreader = CMD.ExecuteReader()
Myreader.Read()
Test123 = Myreader("FebQTY")
There are 180 rows when I copy/paste my query into SQL Developer, however whenever I try to use this in VB.NET to populate my listview, I was getting nothing. So I tossed it into the above code just to see what I was quickly getting back from FebQTY and the error is that there are no rows, same with mti_part_no. Can't figure out what the problem is.
I have a Dataset called 'ds' and I want to put that dataset into one of my tables in my sql database. I cannot seem to find a solution for this. How would I go about putting the dataset into a table? Any help would be greatly appreciated!
Code so far. Dataset that is created from user input:
Dim ds As DataSet = CreateNewDataSet()
Dim entries As New List(Of String())
Console.WriteLine("Enter first name: ")
firstName = Console.ReadLine()
Console.WriteLine("Enter last name: ")
lastName = Console.ReadLine()
entries.Add({firstName, lastName})
entries.ForEach(Sub(x) ds.Tables(0).Rows.Add(x))
I'm only using one table, 'Person' with the fields 'firstname' and 'lastname'.
Trying to insert dataset into table Person:
Using connection = New OleDbConnection("connectionstring")
connection.Open()
Dim adapter = New OleDbDataAdapter()
Dim myQuery As String = String.Empty
myQuery &= "INSERT INTO Applicant (strFirstName, strLastName)"
myQuery &= "VALUES(?, ?)"
adapter.InsertCommand = New OleDbCommand(myQuery, connection)
adapter.InsertCommand.Parameters.AddWithValue("#strFirstName", firstName)
adapter.InsertCommand.Parameters.AddWithValue("#strLastName", lastName)
adapter.Update(ds)
End Using
This is the solution:
Private Function CreateObject(ds as DataSet)
Dim connection as OdbcConnection = new OdbcConnection(conString)
connection.Open()
Dim adapter as OdbcDataAdapter = new OdbcDataAdapter("select * from Table", connection)
ds = new DataSet("DefaultName")
adapter.FillSchema(ds, SchemaType.Source, "Table")
adapter.Fill(ds, "Table")
Dim table as DataTable
table = ds.Tables("Table")
Dim row as DataRow = Nothing
row = table.NewRow()
row("field1") = varField1
row("field2") = varField2
table.Rows.Add(row)
Return ds
End Function
Find below what I've done so far, but unfortunately it's not working.
Private BS as New BindingSource
Dim ds As New DataSet
' Make the Connection
Using con As New OleDb.OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = Database1.mdb")
con.Open()
Dim Sql = "SELECT COUNT ([Eventname]) FROM Eventproposal"
Dim da = New OleDb.OleDbDataAdapter(Sql, con)
da.Fill(ds, "Eventproposal")
' Set the Binding Source
bs.DataSource = ds.Tables("Eventproposal")
con.Close()
End Using
TextBox1.DataBindings.Add("Text", bs, "")
Couple things, you should end all SQL Commands to MS Access with ;
Dim Sql = "SELECT COUNT ([Eventname]) FROM Eventproposal;"
And you did not name your column which will give you an error when you attempt to access it by name.
Dim Sql = "SELECT COUNT ([Eventname]) AS Eventname FROM Eventproposal;"
I believe it will give it a name but not what your thinking. Lastly, when you do your binding, you will have to reference the name of the field in the table.
TextBox1.DataBindings.Add("Text", bs, "Eventname")
This is what I've got so far :
Dim myCONN As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\Baza.mdb")
Dim cmd1 = New OleDbCommand("SELECT ID FROM Baza WHERE NAZIV=#XXNAZIV")
cmd1.Parameters.AddWithValue("#XXNAZIV", TextBox2.Text)
cmd1.Connection = myCONN
myCONN.Open()
Dim result = cmd1.ExecuteReader()
While (result.Read())
Dim rowx As Integer = GetTextOrEmpty(result("ID"))
End While
I've found the row (rowx) in which I would like to change values in 20 corresponding columns (namesID : NAZIV, SIFRA,...). Data is already presented in textboxes (textbox1...), but I don't know how to finish this code with UPDATE and how to insert changed values back to Access.
Dim cmdText As String = "UPDATE Baza SET NAZIV=#XXNAZIV Where ID=SomeId"
Using con = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = h:\Baza.mdb")
Using cmd = new OleDbCommand(cmdText, con)
con.Open()
cmd.Parameters.AddWithValue("#XXNAZIV",TextBox2.Text)
cmd.ExecuteNonQuery()
End Using
End Using
This should help you to solve your problem, of course you will have to pass ID parameter to query also.
Reference
I want to select a certain field from a datatable in VB based on the value of another field in the same row.
In SQL, it would easily be done by writing this query:
select error_message from table_errors where error_case="condition"
How do I do this if I have my SQL table filled in a datatable in VB?
How do I select the item("error_message") in the datatable based on the item("error_Case") field?
Any help would be appreciated
You can use Linq-To-DataSet:
Dim matchingRows As IEnumerable(Of DataRow) =
From row In table
Where row.Field(Of String)("error_case") = "condition"
If you just want one column (of course that works also in one step):
Dim errorMessages As IEnumerable(Of String) =
From row In matchingRows
Select row.Field(Of String)("error_message")
For Each error In errorMessages
Console.WriteLine(error)
Next
If you expect it to be just a single row use First or Single(throws an exception if there is more than one row):
Dim error As String = errorMessages.First()
Since First throws an exception if the sequence is empty you can use FirstOrDefault:
Dim error As String = errorMessages.FirstOrDefault() ' is null/Nothing in case of an empty sequence
All in one line (note that both Linq and DataTable.Select needs to use loops):
Dim ErrMessage As String = errorTable.AsEnumerable().
Where(Function(r) r.Field(Of String)("Error_Case") = TextCase.Text).
Select(Function(r) r.Field(Of String)("Error_Message")).
FirstOrDefault()
here is a worker version of the rough code
Dim connString As String = "select error_message from table_errors where error_case='condition'"
Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(connString)
conn.Open()
Dim cmd As SqlClient.SqlCommand = New SqlClient.SqlCommand(connString, conn)
Dim dTable As DataTable = New DataTable()
Dim dAdapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(cmd)
dAdapter.Fill(dTable)
conn.Close()
Dim text As String
Dim dReader As DataTableReader = dTable.CreateDataReader()
While dReader.Read()
text = dReader.GetValue(0)
End While
dReader.Close()