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
Related
What is the alternative option to pass the connection string in below vb code to get rid of external Control of system setting
Protected ConnectString As String
ConnectString = Session ("Oracle_ConnectString").ToString()
Dim OracleConnection_A As New Oracle.DataAccess.Client.OracleConnection(ConnectString)
It says never allow untrusted data and validate untrusted input using central data validation to fix the flaw.. please guide to fix this error
Thanks
As a general rule, for desktop or web, we always used the project property->settings, and used this:
I WOULD NOT use session() as that can be rather flakey.
Any setting you use above? Well, now you can use either the configeration manager, or just use the built in class that VS generates for you!!!
So in code, use the settings class (which is automatic created for you).
Then your code to say load up a grid would look like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid
End If
End Sub
Sub LoadGrid()
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand("SELECT * FROM Fighters", conn)
conn.Open()
Dim rstData = New DataTable
rstData.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = rstData
GridView1.DataBind()
End Using
End Using
End Sub
So, I used the My.Settings for this.
And if you look, that setting is shoved into web.config for you.
And REALLY nice is that project settings has a connection string wizard/builder that you can use - so no need to build + create the connection string - VS will do all the dirty work for you.
And, if you want, I suppose you can use the confirmation manager.
So, in the code you have "Imports System.Configuration"
So now this:
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand("SELECT * FROM Fighters", conn)
can be this:
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("TEST4").ConnectionString)
Using cmdSQL As New SqlCommand("SELECT * FROM Fighters", conn)
ETC.
So, you can manually enter the connection strings into the web.config, but I would suggest that using the My.Settings class (which is automatic built for you) is a far easier approach here. The nice part is the project->properties settings can also have simple number settings, tax rates - even the company name or whatever. Once again, this is really like app-settings in a desktop application. And while sometimes I don't like these obfuscated class systems? For application settings? I think it is a great idea, and better yet it means the years of doing this say for desktop applications now is exactly the same approach for web based applications.
but, no, I don't suggest using session() for connection strings - a bad idea, and bad place since session() can be lost quite easy - especially if you using memory based vs sql server based ones.
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.
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 have attempted to make my first 3 tier application. In the process I have run into one problem I am yet to find an optimal solution for.
Basically all my objects use an IFillable interface which forces the implementation of a sub as follows
Public Sub Fill(ByVal Datareader As Data.IDataReader) Implements IFillable.Fill
This sub then expects the Ids from the datareader will be identical to the properties of the object as such.
Me.m_StockID = Datareader.GetGuid(Datareader.GetOrdinal("StockID"))
In the end I end up with a datalayer that looks something like this.
Public Shared Function GetStockByID(ByVal ConnectionString As String, ByVal StockID As Guid) As Stock
Dim res As New Stock
Using sqlConn As New SqlConnection(ConnectionString)
sqlConn.Open()
res.Fill(StockDataLayer.GetStockByIDQuery(sqlConn, StockID))
End Using
Return res
End Function
Mostly this pattern seems to make sense. However my problem is, lets say I want to implement a property for Stock called StockBarcodeList. Under the above mentioned pattern any way I implement this property I will need to pass a connectionstring to it which obviously breaks my attempt at layer separation.
Does anyone have any suggestions on how I might be able to solve this problem or am I going about this the completely wrong way? Does anyone have any suggestions on how I might improve my implementation? Please note however I am deliberately trying to avoid using the dataset in any form.
Use the app.config file for your connection string.
Is there a particular reason you pass ConnectionString at all? It seems like a configuration value to me? So using something like a constant (or a Config singleton) might be a better idea.