Use SQL IN inside vb.net dataset adaptor - asp.net

I'm trying to use a dataset adapter in my asp.net/vb.net website. But I need to search using multiple values, Ideally, i'd just like to pass an in statement in to my dataset adapter. Is this possible, as how it is, it doesn't seem to bring back anything:
Heres my data adapter:
The query is:
select * from joblist where username in (#username)
I'm trying to call it with:
Private dtJobs As Barry.joblistDataTable
Private taJobs As New BarryTableAdapters.joblistTableAdapter
dtJobs = New Barry.joblistDataTable
dtJobs = taJobs.FilterSearch("'tomb','martinm','chrise'")
rptJobList.DataSource = dtJobs
rptJobList.DataBind()
What am I doing wrong?

You're passing in a comma separated string, a single parameter. You cannot use it as is in an IN statement.
You have to split it into table, for example using this solution. Using this function (I assume you're using SQL Server as your DB) you can rewrite your query as:
select joblist.* from joblist
inner join dbo.Split(',', #username) t
on joblist.username = t.s
This approach splits your multi-value parameter into table and joins to the original table

Related

Transfer Array into SQLite and vice versa without looping especially in ActionScript3

I am very new to programming in ActionScript3 and using SQLite. Currently I try to make an AIR application where it will handle from small to large dataset from excel, import into and calculate in AIR using ActionScript3 and stored the calculated data in SQLite.
Right now I have 2 question regarding using array to transfer data into SQLite
1. Is it possible to INSERT data or UPDATE data in SQLite without using looping?
In my AIR application, I have an object called DataInput in which have 62 variables/properties which will contain 62 different values from 62 columns in excel. I do know that if you create new instance of DataInput and push into array e.g arDataInput in loop, you can access each of the data in the array using arDataInput[i].variablename where i is the index of the array and variablename is the variables/properties of the object.
Obviously, right now I do actually using for loop to access the value of each cell in excel then calculate in AIR application before transfer the calculated data into SQLite, row by row within sql transaction.
Is there actually a way to transfer data in array into SQLite (either INSERT new row or UPDATE existing row) without using loop like INSERT INTO tblDataInputUW VALUES arDataInput given that each column name in SQLite table is the same as variables/properties of object within the array eg. SQLite table, tblDataInput have column name namePlat and array have variables/properties of arDataInput.namePlat?
2. Is it possible to split the data array i got from SQLite into multiple array without looping?
Right now, I use the following code to extract data from SQLite and stored as an array;
txtSQL = new String();
arData = new Array();
txtSQL = "SELECT namePlat, platLat, platLong FROM tblDataInput";
arData = getSQLData(txtSQL);
function getSQLData(text: String): Array
{
sqlCon.begin();
sqlStat = new SQLStatement();
sqlStat.sqlConnection = sqlCon;
sqlStat.text = text;
sqlStat.execute();
sqlCon.commit();
var result: SQLResult = new SQLResult();
var arData: Array = new Array();
result = sqlStat.getResult();
if (result != null)
{
arData = result.data;
}
return arData;
}
If my assumption are correct, I can access each of the value in arData by using arData[i].variablename where i is the index of the array and variablename is the table name within the SQLite table tblDataInput.
If there are way to split the data in arData into 3 different array e.g arNamePlat without using looping like arNamePlat = arData.variablename because I have many different chart to draw in my AIR application and each chart will have its own array to get value from.
Right now, I actually using different sql statement for different chart like;
txtSQL = new String();
arData = new Array();
txtSQL = "SELECT namePlat FROM tblDataInput";
arData = getSQLData(txtSQL);
dgNamePlat.dataProvider = new DataProvider(arData);
txtSQL = new String();
arData = new Array();
txtSQL = "SELECT platLat, platLong FROM tblDataInput";
arData = getSQLData(txtSQL);
dgPlatLatLong.dataProvider = new DataProvider(arData);
I use the same arData and txtSQL for each chart as I dont store the value anymore after the chart been drawn.
There are actually no restriction for me to just use for loop, I asking this question as I don't see any topic regarding on this question and as a self-learning programmer, I like to explore different way of coding and way to incorporate that knowledge into my projects.
The best way to send and receive data and do database stuff is through form submissions. AIR can POST regular form submissions like html pages but can also load a response. Regular serverside software like php handles the form submission, does whatever with the database, and returns data or simple success message.
The best way to handle data is to use XML (look into RESTful architecture for reasons why). PHP creates XML for the app. The xml gets loaded and should go into arrays of objects.
Here are some good links to get going on submitting data with forms and reading XML:
republic of code tutorials:
http://www.republicofcode.com/tutorials/flash/as3contactform/2.php
http://www.republicofcode.com/tutorials/flash/as3xml/
https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLRequest.html
https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLRequestMethod.html

What do I need to learn for accessing data from mssql database?

I am learning asp.net core mvc and API. I can simply work on it for CRUD operation. But, I get confused for accessing data from multiple tables like listing all categories with showing number of items each categories contains. What I need to learn for example Lina, entity framework code first, ado.net? I am currently using entity framework code first.
Thanks
Learn Dapper a simple object mapper for .NET.
What I Understood from your problem is that you have multiple tables and you want to query them and map the query result in your c# or vb code.Here I will show simple mapping of query result to c# objects.
Suppose you have three tables category_1,category_2 and category_3.
Lets say each table have two columns named itemName and ItemValue.
Lets create c# class corresponding to each table.
class category_1{
string ItemName {get;set};
int ItemValue {get;set;};
}
class category_2{
string ItemName {get;set};
int ItemValue {get;set;};
}
class category_3{
string ItemName {get;set};
int ItemValue {get;set;};
}
Suppose your querying three tables and map the result of query to respective object in c#.
let our sql query be as follows:
string sql = #"select * from category_1;select * from category_2;select * from category_3;"
Here we have three select statements and each select statement will give you result of respective table.Lets query the above sql to database using dapper and map them to c# object as follows.
List<category_1> lstCotegory1 = new List<category_1>();
List<category_2> lstCotegory2 = new List<category_2>();
List<category_3> lstCotegory3 = new List<category_3>();
using (var multi = connection.QueryMultiple(sql))
{
lstCotegory1 = multi.Read<category_1>().ToList(); // map first select statement
lstCotegory2 = multi.Read<category_2>().ToList(); // map second select statement
lstCotegory3 = multi.Read<category_3>().ToList(); // map third select statement.
}
This is how you can return results of multiple queries and map them to appropriate object. I know you can do better than this but to understand we have to go with simple example.Hope this will help.

NHibernate: adding calculated field to query results

I have inherited an ASP.NET website built on NHibernate, with which I have no experience. I need to add a calculated field based on a column in a related table to an existing query. In SQL, this would be done easily enough using a correlated subquery:
select
field1,
field2,
(select count(field3) from table2 where table2.table1ID = table1.ID) calc_field
from
table1
where
[criteria...]
Unfortunately, of course, I can't use SQL for this. So in reality, I have three related questions:
What is the best way to trace through the web of interfaces, base classes, etc used by NHibernate in order to pinpoint the object where I need to add the field?
Having located that object, what, if anything, has to be done besides adding a public property to the object corresponding to the new field?
Are there any NHibernate-specific considerations with regard to referencing a related object in a query?
Here is the existing code that performs the search:
public INHibernateQueryable<C> Search(ISearchQuery query, string sortField)
{
_session = GetSession();
var c = _session.Linq<C>();
c.Expand("IP");
c.Expand("LL");
c.Expand("LL.Address");
c.Expand("LL.Address.City");
c.Expand("LL.Address.City.State");
c.Expand("LL.Address.City.County");
c.Expand("CE");
c.Expand("IC");
c.Expand("AR");
c.Expand("ER");
c.Expand("Status");
var res = _SearchFilters
.Where(x => x.ShouldApply(query))
.Aggregate(c, (candidates, filter) => (INHibernateQueryable<C>) filter.Filter(candidates, query));
res = SortSearch(res, sortField);
return res;
}
I appreciate any advice from experienced Hibernators.
Thanks,
Mike
If you are only interested in returning a query containing a computed value, you can still call a stored procedure in NHibernate and map the results to a POCO in the same way as you map a table for CRUD operations; obviously read-only instead of updatable.
Have a look at the ISession.CreateSQLQuery method; I can post an example from one of my projects if you need one.

DataTableMapping using adapter.FillSchema method applied on a Stored Procedure

this is a method i was reading about #MSDN ,
my question is if for an example i would like to use it on a stored procedure
with the fact that the query of that stored procedure is already specifying columns to select from the table like following :
SELECT Columnsome, columnother, , , , ...FROM thisSQLdbTable
though i would like to implement the approach of that specific method , it seems very advanced from a little research i have made on
"the best way" available to extract data from SQL Server into Asp.net DataTable.
public static DataTable GetCustomerData(string dataSetName,
string connectionString)
{
DataTable table = new DataTable(dataSetName);
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT CustomerID, CompanyName, ContactName FROM dbo.Customers", connection);
DataTableMapping mapping = adapter.TableMappings.Add("Table", "Customers");
mapping.ColumnMappings.Add("CompanyName", "Name");
mapping.ColumnMappings.Add("ContactName", "Contact");
connection.Open();
adapter.FillSchema(table, SchemaType.Mapped);
adapter.Fill(table);
return table;
}
}
or is it not the method to use if i am querying via SP that specifies the selected column
i could actually drop that stored procedure if it is not requiered to select /specify columns
the stored procedure is doing a specific calculation and updates the table with results of calculation then i am switching it's "MODE" to select results from the table that was updated.
what i did is recyceling (; giving it a parameter (bit type)
stored procedure then asks for the value of supplied bool / bit Parameter,
if its is status true it updates (doing its original task it was made for)
if its false its doing a select oporation so i am using it as i would with 2 separated commands
but now that i have search for a better way to extract data from db into a Data table
i give up on the two way SP and i will make a selection via the exaple above if they're not intended to be used thogether as with my current SP that does preselection when servs the GetCustomersData() above.
So the question is do i need to let the function to make the selection or can i serve it with my sp ready made selection to implemet it with GetCustomersData() in the way that it will only do rest of task and only mapp the columns that was preselected
Still a bit confused on your actual requirement but here goes:
I See you are using a direct query in your C# code, 'best way' would be to make a SP out of it then say:
SqlCommand command = conn.CreateCommand();
SqlDataAdapter sqlAdapter = new SqlDataAdapter(command);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "sp_GetCustomerData";
Then after you have added parameters if needed do:
conn.Open();
sqlAdapter.Fill(dtResult);
conn.Close();
Where dtResult is Datatable.
So you do not need to do any mapping in this case, and since you are using a SP from the Database it will work faster than your direct query and you can change the query logic any time without the need of re deploying your code.
Stored procedures are perfectly valid in this use case. however, if you want more of a properly mapped table, you have several options, some of which go beyond the use of DataTables.
You can use strongly typed DataSets or perhaps use an ORM (object relational mapper).
ref: Typed Datasets: http://msdn.microsoft.com/en-us/library/esbykkzb(v=vs.71).aspx
ref: What is an ORM : http://en.wikipedia.org/wiki/Object-relational_mapping
EXAMPLES OF ORM'S
ref: Entity Framework : http://msdn.microsoft.com/en-us/data/ef.aspx
ref: NHibernate: http://nhforge.org/

Using arraylist to insert items into DB

I have created an ArrayList with items in my Order.aspx.vb. I pass these on to my bllOrder, which passes it on to my dalOrder.
Order.aspx.vb
Dim item As RepeaterItem
For Each item In rptProductList.Items
objOrder.OrderCustID = Session("CustID")
objOrder.OrderProdID = DirectCast(item.FindControl("ddlProducts"), DropDownList).SelectedValue
bllOrder.InsertOrder(objOrder)
Next item
dalOrder
Function InsertOrder(ByVal objOrder As Order) As Boolean
Dim Result as New Boolean
myconn.open()
Dim SQL As String = "INSERT INTO order(OrderCustID, OrderProdID) VALUES (?,?)"
Dim cmd As New OdbcCommand(SQL, myconn)
cmd.Parameters.AddWithValue("OrderCustID", objOrder.OrderCustID)
cmd.Parameters.AddWithValue("OrderProdID", objorder.OrderProdID)
result = cmd.ExecuteNonQuery()
myconn.close()
Return Result
End Function
This is good for one item, but how would I do it for my ArrayList?
All help is much appreciated!
instead of passing single Order item, pass a List of Orders and them loop it though inside your method. make it like that Public Function InsertOrder(objOrder As List(Of Order)) As Boolean and then use objOrder as a list of Orders to loop it through.
put the following code inside a foreach loop following code and pass the current item values;
cmd.Parameters.AddWithValue("OrderCustID", objOrder.OrderCustID)
cmd.Parameters.AddWithValue("OrderProdID", objorder.OrderProdID)
result = cmd.ExecuteNonQuery()
Convert the array of items into an xml string and you can do a bulk insert in the stored procedure using openxml. http://msdn.microsoft.com/en-us/library/ms191268.aspx also refer an older post for sql server 2005 http://weblogs.asp.net/jgalloway/archive/2007/02/16/passing-lists-to-sql-server-2005-with-xml-parameters.aspx
** edited to account for extra info **
You could adapt the existing "for each" logic in your codebehind to build an arraylist or List<> of products - this array/list should be a property of your Order object. Pass the Order object to the DAL via your BAL as currently.
Then iterate through the products in the Order object in the DAL code(InsertOrder) and either
insert each row individually in a
loop
or dynamically build an insert statement for the Order
.
You should wrap it in a transaction to ensure the order is rolled back competely if one row fails to insert.
For orders with large amout of products i'd go for #Aravind's answer.
I’d use SqlClient.SqlBulkCopy. This is effectively a .Net version of Bulk Insert, to use it you need to either have your objects you want to insert in a either a DataTable or create a class to read your data that implements IDDataReader. If your inserting 1,000’s of rows then you should see a dramatic performace increase and much tidier code.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx
Please go through the following link
How to insert a c# datetime var into SQL Server
I will suggest you to use the comma seperated values . Do not send the array list in your DAL Layer instead a function should return a formatted comma seperated value from the Presentation Layer and send this value to DAL and finally seperate the values in your stored procedure.
Alternative
You can format your values in an XML and send it to Stored Procedure.
In order to perform it your parameter should be of varchar type.

Resources