I ask the above question because I am seeing something property HasRows in the QuickWatch window..
I am modifying someone else's code, and need to follow the patterns established. I have to query a SQL Server table to retrieve a row from a configuration table, and decided to first code it in a test console app. I also decided to use the SQLClient types, and made use of property HasRows:
....
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
....
When I went to move the code to the other project, I noticed that IDataReader was used, and Intellisense said that the HasRows property wasn't available, so I used a while loop, even though I only have one row returning:
....
using (IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
....
However when I performed a quick watch on the IDataReader rdr, I saw the HasRows property!
So can I easily get to the HasRows property for the IDataReader? If it really exists?
No you can't. HasRows is an abstract method of DbDataReader and IDataReader don't have it.
Even so DbDataReader implements IDataReader it is implemented inside DbDataReader and not in interface itself.
Use DbDataReader in your code instead of interface.
Related
I want to show the Database Values in a table in asp.net.
The below code is a simple query:
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = new SqlConnection("");
cmd.CommandText = "SELECT * FROM Customers ORDER BY CustomerID";
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
How can the table demonstrate DB Values? (Code needed)
You have several missing pieces in your code such as missing connection string, not relating the command to the connection and using ExecuteNonquery.
This is a good example of what you want to do: MSDN-DataGridView DataSource. While the example is not for Windows Forms, the same code for data access in the method GetData still applies.
in your application you could use the filled table (from the example) as in:
MyDataGrid.DataSource = GetData("Select * from Customer")
MyDataGrid.DataBind();
Alternatively, You can also use Visual Studio environment to connect your data grid view to the DataSource without writing code.
The above is just a simple example there are different better ways to do the same thing. However, this is a start.
As others have mentioned in the comments, you need a DataList, Gridview or Repeater on your page to bind to this data. Without it you're connecting but not displaying what you get.
The easiest thing to do would be drop a Gridview on the page and set its datasource to your command object. You need to define a CommandType on the command, too, or you'll probably throw an error.
GridView1.DataSource = cmd;
GridView1.DataBind();
You're also missing a Try...Catch...Finally with the Close() call in the Finally block. If you don't do that you could wind up with zombie connections that'll trash performance in your database.
Like the title suggest, I would like to ask, is there any other way to store data from database, other than using dataset or datatable in ASP.NET?
I'm currently using something like this:
Public Function openDataTable(ByVal query As String) As DataTable
Try
If con.State <> ConnectionState.Closed Then con.Close()
con.Open()
dt = New DataTable
adap = New SqlDataAdapter(query, con)
adap.Fill(dt)
con.Close()
Catch ex As Exception
MsgBox.Message)
End Try
Return dt
End Function
dt = conn.openDataTable("Select * From Employee")
It worked fine for me, but I would like to know, is there any other way to do it?
And if there is another way, would someone be so kind as to give me an example? Thanks.
In .net framework 3.5 and above you can use linq with entity framework.
Start here:
Getting Started with LINQ in C#
Entity Framework
A very good Entity framework Tutorial: http://www.codeproject.com/Articles/363040/An-Introduction-to-Entity-Framework-for-Absolute-B
Introduction to LINQ: http://msdn.microsoft.com/en-us/library/bb397897.aspx
Getting Started with LINQ in Visual Basic
Yes. You could:
Run SQL Statements directly
Use Linq to SQL
Use Entity Framework
I wrote this type of command for my application.BUT my lecturer told me those things are Old fashion,USE new things like DATASET.. I wanted to know you guys is that correct ? Those kind of thigs are outdated ? Date Set is new way to do this ?
protected void btn_edit_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(CONN_STR))
{
con.Open();
using(SqlCommand cmd = new SqlCommand("UPDATE tbl_BinCardManager SET ItemName = #ItemName WHERE ItemNo = #ItemNo"), con)
{
// TODO: fill in param values with real values
cmd.Parameters.AddWithValue("#ItemName", "my item name");
cmd.Parameters.AddWithValue("#ItemNo", 1);
cmd.ExecuteNonQuery();
}
}
}
The classes you are using are the nuts and bolts of pretty much all data access technologies in .NET. There are abstractions around it such as DataSets, LINQ to SQL, Entity Framework, etc. But in the end they all use SqlConnection and friends.
In fact, of the 3 technologies I mentioned, DataSets are the ones that have been largely discarded and have little or no support outside of the .NET 2.0-era tooling.
DataSet used DataReader internally to populate date. Also dataset works in disconnected mode, but your code is not outdated by any means.
Your teacher is may be talking about using ORM.
NO, your code is not at all Old fashioned..its perfectly simple for your requirement.
use DATASET when its really needed.. like, when you want to take some data offline, and modify it and again reflect back the changes to database..
In fact SqlCommand command is not an alternative for DATASET..
DATASET is something which can hold tables retrieved from database or locally created..
SqlCommand is something which helps you get/insert/update data from/to database table
even if you are using DATASET you still need SqlCommand.. then there is no question of Sqlcommand being oldfashioned and Dataset being the new one
The ASP.NET web application I am developing needs to support two different types of databases, namely Access and MS SQL Server 2008 Express.
I already have connection strings for each database type stored in web.config, and I have another web.config value that specifies which one to use. So I can get the proper connection string with no problem.
The big problem comes with the database objects. For Access, which I have already implemented, I am using the objects OleDbConnection, OleDbCommand and OleDbDataReader in the code to make the database calls.
It appears that for SQL Server, I can't use those objects, but rather I would need to use the objects SqlConnection, SqlCommand and SqlDataReader to do essentially the same things.
I want to reuse as much of my current code as possible and not have to create two separate blocks for each database type. (I have a lot of methods that take an OleDbDataReader as a parameter - I do not want to have to make 2 of each of those methods, for example.)
I noticed that the connection objects both inherit from DbConnection. And the same is true for the data readers (DbDataReader) and the commands (DbCommand).
Would it be possible to take my existing code for Access, replace all of the Ole objects with the Db objects, and then cast those objects as the proper type depending on the current database type?
Are there any best practices for supporting two database types in one ASP.NET application?
I can add some of my code if that would help. Thanks.
Yes, from framework 2.0 all data readers inherit from the DbDataReader class, so your methods could take a DbDataReader isntead of an OleDbDataReader, and you could use the methods with any database.
However, the databases have different dialects of SQL, so you either have to stay on a narrow path of features that work in all databases that you use, or have separate queries for some tasks.
A specific example of differences is that Access uses data literals like #2010-09-24# while SQL Server uses date literals like '2010-09-24'. Generally most that has to do with dates differs.
The link you're likely missing is the functionality of the DbProviderFactories class. Using this class (and associated helpers also in System.Data.Common), you can abstract the provider and use references to the base classes (such as DbConnection and DbCommand) to do the work. It'd look something like this:
private void DoSomething(string provider, string connectionString, string something)
{
DbProviderFactory factory = DbProviderFactories.GetFactory(provider);
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
DbCommand command = connection.CreateCommand();
command.CommandText = something;
DbDataReader reader = command.ExecuteReader();
//etc...
}
The provider name is a bit tricky to acquire, but should be the invariant class name that matches one of those returned by DbProviderFactories.GetFactoryClasses(). Or, you can simply hard code them. They don't change much, but it is a magic string embedded in your code and may cause issues eventually.
Additional features can be accessed through factory.CreateCommandBuilder that can help you traverse the differences in how the providers handle things like parameters and such.
First of all, let me state I'm very new to EF. With that said, here's my dilemma:
There will be an ASP.NET App migrated to ASP.NET MVC. I would like to utilize EF for this. There is one main database which stores "client information". Apart from that, every "client" has their own database. These are the constraints we have.
Currently, client information in the main DB that enables me to build a connection string per client and make individual SQL calls.
How would I accomplish the same thing in Entity Framework? Each database WILL have the same schema. Is there a way to programmatically switch the Connection String? These DBs are currently on the same server, but that's not a requirement and it may be a completely different server.
Any ideas?
Multiple connection strings in the Web.config would be a last resort. Even then, I'm not sure how exactly to wire this up.
Thank you in advance.
If you work through an EntityConnection in the constructor of your entities object, you can change the database pretty easily.
EntityConnection con = new EntityConnection(connString);
con.ChangeDatabase(dbName);
using (Entities context = new Entities(con))
{
// Some code here
}
When you build a data context, here's how to programmatically change the connection string at runtime by modifying the Context.Connection property:
//Get the connection string from app.config and assign it to sqlconnection string builder
SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(((EntityConnection)context.Connection).StoreConnection.ConnectionString);
sb.IntegratedSecurity = false;
sb.UserID ="User1";
sb.Password = "Password1";
//set the object context connection string back from string builder. This will assign modified connection string.
((EntityConnection)context.Connection).StoreConnection.ConnectionString = sb.ConnectionString;
Taken from: http://sivapinnaka.spaces.live.com/blog/cns!B027EF7E7070AD69!211.entry
If the number of your customers is limited and the connection strings hardly ever change, an elegant way might be to use ConfigurationManager.ConnectionStrings to retreive the connection string needed.
Like
string connectionString = ConfigurationManager.ConnectionStrings["Miller"].ConnectionString;
return new Entities(connectionString);
See also
http://msdn.microsoft.com/en-us/library/ms254494.aspx