How to connect to multiple databases in asp.net using SqlDataReader? - asp.net

How to connect to multiple databases in asp.net using SqlDataReader?
Assume that I have two databases such as “Product” and “people”. The product database has two tables, let’s say table1 and table 2, while people has two tables, let’s say again table1 and table2.
I want to get some information from Product.table1 and some from people.table2.
I tried with the following code, but unfortunately it does not work:
SqlConnection con1 = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Product.mdf;Integrated Security=True");
SqlConnection con2 = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\People.mdf;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand("select prod_name, prod_price from product_tbl", con1);
SqlCommand cmd2 = new SqlCommand("select std_name from student_tbl", con2);
con1.Open();
con2.Open();
SqlDataReader dr1 = cmd1.ExecuteReader();
SqlDataReader dr2 = cmd2.ExecuteReader();
// GridView1.DataSource = How to do it??
GridView1.DataBind();

You can either do it as follow :
Retrieve the result from Product DB in dataset1
Retrieve the result from People DB in dataset2
Use DataSet.Merge Method to merge the two data sets in a single dataset say dsProductPeople
Bind dsProductPeople to the grid
OR you can use following example :
// Assumes that customerConnection is a valid SqlConnection object.
// Assumes that orderConnection is a valid OleDbConnection object.
SqlDataAdapter custAdapter = new SqlDataAdapter(
"SELECT * FROM dbo.Customers", customerConnection);
OleDbDataAdapter ordAdapter = new OleDbDataAdapter(
"SELECT * FROM Orders", orderConnection);
DataSet customerOrders = new DataSet();
custAdapter.Fill(customerOrders, "Customers");
ordAdapter.Fill(customerOrders, "Orders");
DataRelation relation = customerOrders.Relations.Add("CustOrders",
customerOrders.Tables["Customers"].Columns["CustomerID"],
customerOrders.Tables["Orders"].Columns["CustomerID"]);
foreach (DataRow pRow in customerOrders.Tables["Customers"].Rows)
{
Console.WriteLine(pRow["CustomerID"]);
foreach (DataRow cRow in pRow.GetChildRows(relation))
Console.WriteLine("\t" + cRow["OrderID"]);
}

Related

Adding '% into SQL Command

I have an SQL Query that i want to run throw my asp.net (WebForms) Project
The Query is:
SELECT COUNT([order]) FROM menu_orders_Finished
WHERE [order] LIKE '%EXAMPLE%'
What i'm trying to do is
con.Close();
con.Open();
cmd = new SqlCommand("select * from menu",con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
Series series = Chart2.Series["Series2"];
while (dr.Read())
{
search = new SqlCommand("SELECT COUNT([order]) FROM menu_orders_Finished WHERE [order] LIKE '%#order#%'", con);
search.Parameters.AddWithValue("#order", dr["name"].ToString());
int count = Convert.ToInt32(search.ExecuteScalar());
Label3.Visible = true;
Label3.Text += count.ToString() + "+";
}
con.Close();
Which is Basically Counting how many times i'm having an order with one my menu items in the order (I want to make a chart of the best selling meal)
And then adding it in the chart (But i toke it off just to see what i get first)
I think you want string concatenation:
search = new SqlCommand("SELECT COUNT([order]) FROM menu_orders_Finished WHERE [order] LIKE CONCAT('%', #order, '%')", con);

multiple SQL commands. Good style?

I got an asp.net application running perfectly fine. in my code i have the following lines
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand getGenreId = new SqlCommand("Select ID from tblGenre WHERE Genre=#newGenre;", con);
getGenreId.Parameters.AddWithValue(#"newGenre", newGenre);
SqlCommand cmd = new SqlCommand("UPDATE tblSong SET Title=#newTitle, ArtistId=#newArtistId, GenreId=#newGenreId WHERE (ID = #songId);", con);
cmd.Parameters.AddWithValue(#"newTitle", newTitle);
cmd.Parameters.AddWithValue(#"newArtistId", newArtistId);
cmd.Parameters.AddWithValue(#"songId", songId);
con.Open();
newGenreId = (int)getGenreId.ExecuteScalar();
cmd.Parameters.AddWithValue(#"newGenreId", newGenreId);
cmd.ExecuteNonQuery();
}
i know database connections are valuable resources and i should be careful when using them. (open as late as possible and make sure they will be closed aswell)
My question now is this code considered bad style because im opening the connection then have as sql query to get an ID and then have another sql query to insert a record.
thanks you!
If you convert to using stored procedure, you can eliminate 1 round trip, therefore reducing network traffic and possibly increase performance.
using (SqlCommand cmd = new SqlCommand("Update_tblSong", con);
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#newGenre", newGenre);
cmd.Parameters.AddWithValue("#newTitle", newTitle);
cmd.Parameters.AddWithValue("#newArtistId", newArtistId);
cmd.Parameters.AddWithValue("#songId", songId);
cmd.ExecuteNonQuery();
}
Proc will be like this, I estimated on your variable size.
CREATE PROC Update_tblSong
(
#newGenre VARCHAR(25)
,#newTitle VARCHAR(50)
,#newArtistID INT
,#songID INT
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #NewGenreID INT;
SELECT #NewGenreID = ID
FROM tblGenre
WHERE Genre = #newGenre;
UPDATE tblSong
SET Title = #newTitle
,ArtistId = #newArtistId
,GenreId = #NewGenreID
WHERE ( ID = #songId )
END;
Overall your code flow seems fine, you are using a single connection to execute multiple (related) commands.
You can improve it further with enclosing your command objects in using statement. Since they implement IDisposable interface, just like your connection object.
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
using (SqlCommand getGenreId = new SqlCommand("Select ID from tblGenre WHERE Genre=#newGenre;", con))
{
getGenreId.Parameters.AddWithValue(#"newGenre", newGenre);
newGenreId = (int)getGenreId.ExecuteScalar();
}
using (SqlCommand cmd = new SqlCommand("UPDATE tblSong SET Title=#newTitle, ArtistId=#newArtistId, GenreId=#newGenreId WHERE (ID = #songId);", con))
{
cmd.Parameters.AddWithValue(#"newTitle", newTitle);
cmd.Parameters.AddWithValue(#"newArtistId", newArtistId);
cmd.Parameters.AddWithValue(#"songId", songId);
cmd.Parameters.AddWithValue(#"newGenreId", newGenreId);
cmd.ExecuteNonQuery();
}
}
Why not use a single query with a subquery for your SQL?
UPDATE tblSong SET Title = #newTitle, ArtistId = #newArtistId, GenreId = (Select top 1 ID from tblGenre WHERE Genre=#newGenre ORDER BY Genre) WHERE (ID = #songId);

button wont save to database it comes to exception error

i made a asp.net site with 3 textboxes and 1 dropdown list and a save button evvry time i click it, it give back An exception of type 'System.NullReferenceException' occurred in Bon-Temps.dll but was not handled in user code.
it give this error on de code line
DataRow drow = ds.Tables["OpdrachtGever"].NewRow();
my question is why??
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["BT-1ConnectionString"].ConnectionString;
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from OpdrachtGever";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "OpdrachtGever");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow drow = ds.Tables["OpdrachtGever"].NewRow();
drow["Naam"] = TextBox1.Text;
drow["Adres"] = TextBox2.Text;
drow["PostCode"] = TextBox3.Text;
drow["AantalPersonen"] = DropDownList1.SelectedItem;
ds.Tables["OpdrachtGever"].Rows.Add(drow);
da.Update(ds, "OpdrachtGever");
You have named your table as
da.Fill(ds, " OpdrachtGever ");
^ ^
but then you refer to it with
DataRow drow = ds.Tables["OpdrachtGever"].NewRow();
without any spaces.
There is a rogue space also on this line
ds.Tables["OpdrachtGever "].Rows.Add(drow);
^
It is not a good idea to have these spaces in your table name because they are not meaningfull for us (humans) and easy to forget. But, for the indexer of the table collection, a space makes a difference. So, when you pass the name with the wrong or missing spaces, the indexer is not able to find your table and returns null .

Comparing cyrillic data from SQL Server table and Excel file with ASP.NET

Using ASP.NET I need to compare data loaded from Excel file with data in SQL Server table. It's data written in cyrillic.
Basically, after script creates an array list filled with data from database table, it opens Excel file, and list data from one of the column. For every data stored in Excel cell, I have to find position in mentioned array list.
I have same data in both sources, but script returns that there are no same data at all. I guess that is something related with cyrillic letters.
Part of the code used for reading Excel cells and comparing with array list looks like this:
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
Page.Trace.Write(getExcelSheetName);
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
con.Close();
foreach (DataRow row in dtExcelRecords.Rows)
{
Response.Write(row[0]);
Response.Write(" ");
Response.Write(MyClass.areasList.IndexOf(row[0])); // always returns -1
Response.Write(Environment.NewLine);
Response.Write("<br />");
}
Can you help me solving this please? Thank you in advance!

Why is my DataSet not populating my GridView

I dont know why my data is not showing in my gridview, if i use an sqldatasource with the same query it works.
cmd.Connection = conn
conn.Open()
cmd.CommandText = "SELECT DISTINCT TOP (100) PERCENT dbo.tblConfig_Agent.FirstName, dbo.tblConfig_Agent.LastName, SUM(dbo.tblData_DeviceByDevice.ACDCount) AS Calls, SUM(dbo.tblData_DeviceByDevice.ACDDuration) AS Seconds, dbo.tblConfig_AgentGroup.Name, dbo.tblConfig_Agent.Pkey FROM dbo.tblData_DeviceByDevice INNER JOIN dbo.tblConfig_AgentGroup ON dbo.tblData_DeviceByDevice.FKDevice2 = dbo.tblConfig_AgentGroup.Pkey INNER JOIN dbo.tblConfig_Agent ON dbo.tblData_DeviceByDevice.FKDevice1 = dbo.tblConfig_Agent.Pkey WHERE (dbo.tblData_DeviceByDevice.MidnightStartDate BETWEEN '4/10/2011' AND GETDATE())GROUP BY dbo.tblConfig_Agent.FirstName, dbo.tblConfig_Agent.LastName, dbo.tblConfig_AgentGroup.Name, dbo.tblConfig_Agent.Pkey ORDER BY Seconds, dbo.tblConfig_Agent.FirstName, dbo.tblConfig_Agent.LastName"
da.Fill(ds, "test")
GridView2.DataSource = ds.Tables("test")
GridView2.DataBind()
conn.Close()
UpdatePanel1.Update()
I think you have to review your Dataset filling method....
DataAdapter
// Assumes that connection is a valid SqlConnection object.
string queryString =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet customers = new DataSet();
adapter.Fill(customers, "Customers");

Resources