ASP.NET C# - using dataset to read one row? - c#

I'm developing a classic WEBForms application in C# and when I have to authenticate the user, I read from SQL database the user data using a query like that:
SELECT userid,username,email,city FROM USERS where username='blablabla' and password='blablabla'
I want to use this sql query in my method that returns a DTO Object that I defined in my UserValue class.
I'm thinking to use a dataset to fill user data executing the query.
Is it the correct approach or is it too expensive and useless to use dataset to read one row from a query?
Can you advice me?
thanks

For getting only one record from database or one by one record from database,"Data Reader" is Good Approach.Check the sites below You can get clear Idea on Data Reader.
http://www.aspdotnet-suresh.com/2012/10/aspnet-difference-between-datareader.html
http://msdn.microsoft.com/en-us/library/haa3afyz.aspx
http://www.akadia.com/services/dotnet_data_reader.html

Here's a code snippet (this is for MS SQL, but other flavors of SQL should be similar) to illustrate what I'm talking about in my comment:
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT userid,username,email,city FROM USERS where username=#username and password=#password", con);
cmd.Paramters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
cmd.CommandType = CommandType.Text;
UserInfo info = new UserInfo();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read(); // get the first row
info.UserID = rdr.GetInt32(0);
info.UserName = rdr.GetString(1);
info.Email = rdr.GetString(2);
info.City = rdr.GetString(3);
}
}
}
This example also shows how to do parameterized queries, which are essential for preventing SQL Injection attacks.
Also, rather than looping through the reader, I check to see if it has rows and if it does I read the first row only (and since you're dealing with user information there should theoretically be only one row) and populate the DTO.
Hopefully this will illustrate my comment to your question.

Related

How do I delete an entire row from a database

How would I delete a row from a sql database, either with stored procedures or without, right now I have tried without, using a button press.
This is what I have so far, _memberid has been sent over from a differnt form from the database(For context).
private void btnDelete_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = Lib.SqlConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete * From Members where MemberId = " + _memberId;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.DeleteCommand = cmd;
adapter.Fill(MembersDataTable); // Im fairly sure this is incorrect but i used it from old code
DialogResult = DialogResult.OK;
}
If you're trying to do a simple ADO.Net-based delete, then it would be somehting like his:
private void DeleteById(int memberId)
{
// or pull the connString from config somewhere
const string connectionString = "[your connection string]";
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand("DELETE FROM Members WHERE MemberId = #memberId", connection))
{
command.Parameters.AddWithValue("#memberId", memberId);
command.ExecuteNonQuery();
}
}
Use parameter to prevent SQL injection.
There are essentially three main things I'm seeing...
One
You don't need the * in the query. DELETE affects the whole row, so there's no need to specify columns. So just something like:
DELETE FROM SomeTable WHERE SomeColumn = 123
Two
There's no need for a SqlDataAdapter here, all you need to do is execute the query. For example:
cmd.ExecuteNonQuery();
The "non query" is basically a SQL command which doesn't query data for results. Inserts, updates, and deletes are generally "non queries" in this context. What it would return is simply the number of rows affected, which you can use to double-check that it matches what you expect if necessary.
Three
Don't do this:
cmd.CommandText = "Delete From Members where MemberId = " + _memberId;
This kind of string concatenation leads to SQL injection. While it looks intuitively like you're using _memberId as a query value, technically you're using it as executable code. It's less likely (though not impossible) to be a problem for numeric values, but it's a huge problem for string values because it means the user can send you any string and you'll execute it as code.
Instead, use query parameters. For example, you might do something like this:
cmd.CommandText = "Delete From Members where MemberId = #memberId";
cmd.Parameters.Add("#memberId", SqlDbType.Int);
cmd.Parameters["#memberId"].Value = _memberId;
This tells the database engine itself that the value is a value and not part of the executing query, and the database engine knows how to safely handle values.
You could use a DataAdapter, but since you aren't using a datatable, it's just easier to do it without like this:
var sql = "DELETE FROM Members WHERE MemberId=#MemberId";
using(var cmd = new SqlCommand(sql, Lib.SqlConnection))
{
cmd.Connection.Open();
cmd.Parameters.Add("#MemberId",SqlDbType.Int).Value = _memberId;
cmd.ExecuteNonQuery();
}
And if you are using Dapper, you can do this:
Lib.SqlConnection.Execute("DELETE FROM Members WHERE MemberId=#MemberId", new {MemberId=_memberId});
If you are still using DataTables, I would highly recommend you look into using this (or something like this) to simplify your database accesses. It'll make CRUD logic on a database a breeze, and your code will me a lot more maintainable because you can get rid of all the odd needs to do casting, boxing/unboxing, and reduce the chances of runtime bugs because of the use of magic strings that happens so often with DataTables (column names). Once you start working with POCO classes, you'll hate having to use DataTables. That said, there are a few places where DataTables are a better solution (unknown data structures, etc), but those are usually pretty rare.

c# SqlDataReader Not Finding Value

My Problem has Been Fixed, My main problem was getting the information from the textbox in the xaml which got erased after that window was closed and another opened. Though the answers did fix my other problems and have made my code much simpler and easier to read. So thank you very much!
So I am Currently working on building a Calendar for a personal project and working on adding events to a Database, this table for Events stores two varchars, and an int (name, description, userid), the userid is a foreign key and is linked to the User Table. When I use the code below to try and pull the userid for the username that the person entered, it tells me that there is no existing value.
using (SqlConnection connection = new SqlConnection())
{
connection.ConnectionString =
"Data Source=calenderserver.database.windows.net;" +
"Initial Catalog=Calender;" +
"User id=*******;" +
"Password=*******;" +
"MultipleActiveResultSets = true";
connection.Open();
SqlCommand com = new SqlCommand("Select UserId from Users Where UserName = #user", connection);
com.Parameters.AddWithValue("#user", UsernameTextBox.Text);
SqlDataReader reader = com.ExecuteReader();
reader.Read();
int userid = reader.GetInt32(1);
messages.Text = "Event Added";
SqlCommand command = new SqlCommand("INSERT INTO [Events] VALUES (#eventname, #eventdesc)", connection);
command.Parameters.AddWithValue("#eventname", name);
command.Parameters.AddWithValue("#eventdesc", description);
command.Parameters.AddWithValue("#userid", userid);
command.ExecuteNonQuery();
reader.Close();
connection.Close();
}
Even though when I run the same command in an actual SQL Query it returns a proper value.
SQL Command
I am completely lost on this and have checked multiple sources and solutions and would really appreciate the help.
You are doing int userid = reader.GetInt32(1); the indexes for the get function are 0 based so you actually need int userid = reader.GetInt32(0); so you get the first column.
That being said, because you are using the first result of the first column you can simplify your code by switching from a data reader to using ExecuteScalar()
SqlCommand com = new SqlCommand("Select UserId from Users Where UserName = #user", connection);
com.Parameters.AddWithValue("#user", UsernameTextBox.Text);
int userid = (int)com.ExecuteScalar();
Try using ExecuteScalar function. Execute scalar returns a single value and I see you only need the user ID.
Take a look at this link .
int userid = (Int32)com.ExecuteScalar();
I Hope it helps!
Indices in GetInt32 are 0-based as per doc, therefore your call should read:
int userid = reader.GetInt32(0);
Change these lines:
SqlDataReader reader = com.ExecuteReader();
reader.Read();
int userid = reader.GetInt32(1);
to:
var userID = com.ExecuteScalar();
Why:
Execute Scalar should be used when your query returns a single value.
Execute Reader returns a collection of data in the form of a DataReader. DataReaders are fast, and you can quickly iterate over them to get the data you need from the database. The connection remains open as long as the datareader is open.
Because you were only getting a single value back from the database, it makes sense to use ExecuteScalar. It's more efficient and too the point.
If you were getting a list of UserID's, then I'd recommend you use a DataReader to iterate through the UserIDs.

Using c# how to retrieve and update thousands of records from a SQL database efficiently

Process
I am writing a C# application which will need to retrieve 4 million records(ID) from a SQL table in database A.
I then need to use each ID to select a row of record each from another SQL table in database B.
Once I have this row I then need to update another SQL table in database C
Questions
What’s the most efficient way to retrieve and store the data in Step 1?
a. Should I load this in a list string?
b. Do you recommend doing batches initially?
What the most efficient way to achieve steps 2 and 3
To retrieve the 4M records you're going to want to use a SqlDataReader - it only loads one row of data into memory at a time.
var cn = new SqlConnection("some connection string");
var cmd = new SqlCommand("SELECT ID FROM SomeTable", cn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var id = reader.GetInt32(0);
// an so on
}
reader.Close();
reader.Dispose();
cn.Close();
Now, to handle two and three, I would leverage a DataTable for the row you need to retrieve and then a SqlCommand on the third database. This means that inside the reader.Read() you can get the one row you need by filling a DataTable with a SqlDataAdapter and the issuing an ExecNonQuery against a SqlCommand for the UPDATE statement.
Another way of writing the above, and it's a bit safer, is to use the using statement:
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var id = reader.GetInt32(0);
// an so on
}
}
that will eliminate the need for:
reader.Close();
reader.Dispose();
and so you could also issue that for the SqlConnection if you wanted.
SQLBulkCopy class might help.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx

Connecting to a Server

Trying to improve my C# to SQL skills... Currently I am using this bit of code to pull data from our application server. I have two different DBA's telling me two other ways to write this, just trying to figure out if this should be improved on or changed. If so, I would really appreciate some kind of examples.
FYI: This code...
db.con(user.Authority)
...Is essentially a 'new sqlconnection' code.
DataTable dtInfo = new DataTable("SomeInfo");
using (SqlConnection con = db.con(user.Authority))
{
string command = "SOME SQL STATEMENT;";
using (SqlCommand cmd = new SqlCommand(command,con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Param", sqlDbType).Value = Param;
con.Open();
cmd.ExecuteNonQuery();
**********
*** OR ***
**********
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Param", sqlDbType).Value = Param;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dtInfo );
}
}
}
So, if I'm understanding the provided information, this is my best route?
using (SqlConnection con = db.con(user.Authority))
{
string command = "SELECT [TBL_EMPLOYEE].[ACTIVE_DIRECTORY] FROM [TBL_EMPLOYEE];";
using (SqlCommand cmd = new SqlCommand(command, con))
{
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
MessageBox.Show(reader["ACTIVE_DIRECTORY"].ToString());
}
}
}
And one last thing... This should prevent the need for
cmd.Dispose();
etc...
The code would depend on the specific query. If the query retrieves rows of data (as a SELECT does), then you would go the da.Fill() route. If it's a query that just makes a change to the database (such as INSERT, UPDATE, or DELETE), then you would use ExecuteNonQuery().
I would not use the SqlDataAdapter version. The version that uses the SqlCommand object and the SqlDataReader will perform better, and allows more insight into the actual data being returned.
// Assumes the following sql:
// SELECT foo, bar FROM baz
// error checking left out for simplicity
var list = new List<SomeClass>();
using(var reader = cmd.ExecuteReader()) {
while(reader.Read()) {
list.Add(new SomeClass {
// NOTE: you can see the columns that the c# is referencing
// and compare them to the sql statement being executed
Foo = (string)reader["foo"],
Bar = (string)reader["bar"]
});
}
}
Later as your level of experiance increases you will be able to use other features of the SqlCommand and SqlDataReader classes in order to ensure that the code executes as quickly as possible. If you start using the SqlDataAdapter route, you will eventually have to relearn how to do the exact same things you have already been doing because the SqlCommand and SqlDataReader have operations that do not exist elsewhere in .NET.
ExecuteNonQuery returns the number of rows effected.
A DataTable is not an efficient way to retrieve that number.
int rowsRet = cmd.ExecuteNonQuery();
SqlCommand.ExecuteNonQuery Method

Very basic database concepts in C#

I am writing a console program in C# and I need to use a database.
I am looking for very basic tutorials on connecting with and using a db from a C# console program. I haven't been able to find anything basic enough yet and I hope people here can help me find the info I need. I've read the material on MSDN, but MSDN assumes basic knowledge about these things that I am still looking for.
I have created a db within VS Express in my project, created tables, and written some starter records into the tables. I'm trying to find out exactly what each of these things is, and how to determine how to apply them in my project:
SQLConnection
SQLConnection class
SQLCommand
SQLDataAdapter
DataSets
Thanks.
Something like:
using System.Data;
using System.Data.SqlClient;
using(SqlConnection connection = new SqlConnection("")){
SqlCommand command = new SqlCommand(#"
insert into
tblFoo (
col1,
col2
) values (
#val1,
#val2
)",
connection
);
SqlParameter param = new SqlParameter("#val1", SqlDbType.NVarChar);
param.Value = "hello";
command.Parameters.Add(param);
param = new SqlParameter("#val2", SqlDbType.NVarChar);
param.Value = "there";
command.Parameters.Add(param);
command.ExecuteNonQuery();
connection.Close();
}
-- Edit:
Though, of course, when you start doing serious things, I recommend an ORM. I use LLBLGen (it costs money, but most definitely worth it).
-- Edit:
SqlConnection
The thing through which you communicate to the database. This will hold the name of the
server, the username, password, and other misc things.
SqlCommand
Something that holds the sql statement you want to send to the server. This may be an 'update' or 'insert' or 'select' or anything. Depending on what it is, you use a different method to execute it, to possible get data back.
SqlDataAdapter
A strange one; it's used specifically to fill a 'DataSet'. It basically does a bit of work for you, adding the information it finds to the set.
DataSet
Not sure how simple you want this. It's just a collection of returned data, in a table-like format, that you can iterate over. It contains DataTables, because some queries can return more than one table. Typically, though, you'll only have one table, and you can bind to it, or whatever.
Create a sqlconnection, Open it, Create a sqlcommand, execute it to get a sqldatareader, voila. You won't need a dataadapter for a simple example.
string connectionString = "...";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string sql = "select field from mytable";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
There's a tutorial on ADO.NET that covers a lot of the things you're looking for at http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson01.aspx. Lesson 1 is mostly background but lesson 2 and onwards goes over SQL client objects.
Another tutorial at http://www.codeproject.com/KB/database/sql_in_csharp.aspx covers some of the basics (SqlConnection, SqlCommand).
I bought a book called Pragmatic ADO.NET.
Well, there are two ways to interact with a SQL Server database in C#. The first is with LINQ, and the second is with the SqlClient library.
LINQ
Ever since .NET 3.0, we've had access to LINQ, which is a pretty impressive ORM and way to deal with collections and lists. There are two different ways that LINQ can work with a database. They are:
LINQ to SQL
LINQ to Entities
Scott Gu has a pretty good tutorial on LINQ to SQL, as well. I'd recommend LINQ to SQL for just getting started, and you can use a lot of that in LINQ to Entities going forward.
A sample select to grab all customers in New York would be:
var Custs = from c in Customers
where c.State = 'NY'
select c;
foreach(var Cust in Custs)
{
Console.WriteLine(Cust.Name);
}
SqlClient
The traditional C# way to hit a SQL Server database (pre-.NET 3.0) has been via the SqlClient library. Essentially, you create a SqlConnection to open up a connection to the database. If you need help with your connection strings, check out ConnectionStrings.com.
After you've connected to your database, you will use the SqlCommand object to interact with it. The most important property for this object is the CommandText. This accepts SQL as its language, and will run raw SQL statements against the database.
If you're doing an insert/update/delete, you will use the ExecuteNonQuery method of SqlCommand. However, if you're doing a select, you will use ExecuteReader and return a SqlDataReader. You can then iterate through the SqlDataReader to get your results.
The following is the code to grab all customers in New York, again:
using System.Data;
using System.Data.SqlClient;
//...
SqlConnection dbConn = new
SqlConnection("Data Source=localhost;Initial Catalog=MyDB;Integrated Security=SSPI");
SqlCommand dbComm = new SqlCommand();
SqlDataReader dbRead;
dbConn.Open();
dbComm.Connection = dbConn;
dbComm.CommandText = "select name from customers where state = #state";
dbComm.Parameters.Add("#state", System.Data.SqlDbType.VarChar);
dbComm.Parameters["#state"].Value = "NY";
dbRead = dbComm.ExecuteReader();
if(dbRead.HasRows)
{
while(dbRead.Read())
{
Console.WriteLine(dbRead[0].ToString());
}
}
dbRead.Close();
dbConn.Close();
Hopefully this gives you a good intro to what each approach does and how to learn more.
In general, I recommend using the Microsoft Enterprise Library for DB access. I've used it in a few projects, and am very fond of it.
See the Data Access Quickstart provided by Microsoft that should help you get started
Also, I've also grown accustomed to writing Extension Methods for extracting data from DataRows. For example, I can do something like this:
//Create an extension method, Value,
//to extract a certain type from a DataRow,
//supplying a default value to be used if DbNull.Value is encountered
DateTime someDateValue = dr["SomeDatabaseField"].Value(new DateTime());
Hope this helps!
See ADO.NET Sample Application
Examples cover
SqlClient
using System;
using System.Data;
using System.Data.SqlClient;
class Sample
{
public static void Main()
{
SqlConnection nwindConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");
SqlCommand catCMD = nwindConn.CreateCommand();
catCMD.CommandText = "SELECT CategoryID, CategoryName FROM Categories";
nwindConn.Open();
SqlDataReader myReader = catCMD.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
}
myReader.Close();
nwindConn.Close();
}
}
OleDb
using System;
using System.Data;
using System.Data.OleDb;
class Sample
{
public static void Main()
{
OleDbConnection nwindConn = new OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");
OleDbCommand catCMD = nwindConn.CreateCommand();
catCMD.CommandText = "SELECT CategoryID, CategoryName FROM Categories";
nwindConn.Open();
OleDbDataReader myReader = catCMD.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
}
myReader.Close();
nwindConn.Close();
}
}
Odbc
using System;
using System.Data;
using System.Data.Odbc;
class Sample
{
public static void Main()
{
OdbcConnection nwindConn = new OdbcConnection("Driver={SQL Server};Server=localhost;" +
"Trusted_Connection=yes;Database=northwind");
OdbcCommand catCMD = new OdbcCommand("SELECT CategoryID, CategoryName FROM Categories", nwindConn);
nwindConn.Open();
OdbcDataReader myReader = catCMD.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
}
myReader.Close();
nwindConn.Close();
}
}

Categories