473,804 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

New to C# - DB question

I am used to using old school ADO where I might create things like:

objConn.Open( sConnectString) ;

objRecordSet.Op en ("Select * from users where UID=' + sUserID + "'",
objConn);

Then I have a recordset collection that I can filter on or step through
etc. based on a specific SQL query.

Is there a similar methodology employed in .NET? I see items like

DataSource
TableAdapter
DataSet

But I do not see a specific method for executing SQL against a specific
table or set of tables. I have my data source defined to my project
and I can drag and drop grid or field views to my form but I do not
want that type of functionality. I want user inputs that I then do a
lookup in my database with.

Can someone point me in the right direction?

Thanks in advance!

Aug 17 '06 #1
11 1578
Hi there,

Yes you are along the right track.
Firstly, you are interested in the System.Data namespace, also known as
ADO.NET
In there you will find a few sub namespaces for specific database
connections, and also some generic classes useful for all database
types.

..NET implements a disconnected architecture, where you will essentially
connect to a DB temporarily, perform some action (select, delete,
update, create), and put the results into some object, then disconnect.
There is a class called "Dataset" which can contain a collection of
"DataTable" s
A dataTable can store the result of a "select" against a database. We
generally use a "DataAdapte r" to manage the SQL for us for simple table
operations (ie. a single table CRUD). A DataAdapter (such as the
System.Data.Sql Client.SqlDataA dapter) can take a DataConnection (such
as a System.Data.Sql Client.SqlConne ction) object, along with some
select statement (eg Select * From sysobjects) as a string, and fill a
data table.

If you want to perform simple database statements that don't return a
whole result set, you can use the DbCommand objects (such as a
System.Data.Sql Client.SqlComma nd).
The command object also takes a connection object, and a string which
is your sql statement. With the command object you have 3 methods, of
which you should concern yourself with just 2 as a beginner:
ExecuteNonQuery () and ExecuteScalar()
The former allows you to just execute some SQL, and it will return the
number of rows affected. The latter option lets you execute some sql
where you expect a single result being returned, known as a 'Scalar'.
Example of this is sql such as "Select Count(*) FROM sysobjects" which
you expect a single integer result, rather than tables with rows.

Anyways, pick which database type you are using and check out the
relative namespace. Note that you can also do quite a lot in design
mode with data adapters and datasets, and this is all very well
documented in MSDN.

Hope this helps,
Steven

Aug 17 '06 #2
Oh also, if you are in a rush and need to complete some DB
functionality, you could always add a reference to the old adodb com
stuff and just use the recordsets you are familiar with. But if you
have time, definately learn the new architecture in .NET.

I remember when I did a .NET subject at uni in 4 years ago when I was
first introduced to it. I came from ASP background and I knew about COM
but not ADO.NET so I did exactly that on my first assignment: completed
the requirements using an ADO recordset! Luckily I was asked to
resubmit, otherwise I'd be cleaning windows for a living now...

Aug 17 '06 #3

Thanks a ton, Steve. What I ended up doing for this little test was:

private void btnSubmit_Click (object sender, EventArgs e)
{
int Privelege;
string SQL;
OleDbDataReader Reader;
string sConnect = "Provider=Micro soft.Jet.OLEDB. 4.0;Data
Source = G:\\Media Manager.mdb";
OleDbConnection objConnection = new OleDbConnection
(sConnect);

if (this.txtPassWd .Text.Length < 1 ||
this.txtUserID. Text.Length < 1)
{
MessageBox.Show ("You MUST fill both fields in!");
return;
}

objConnection.O pen();

try
{
SQL = "Select * from Users where username='" +
this.txtUserID. Text + "' AND password='" + this.txtPassWd. Text + "';";
// Find USER ID in users table
// if we find it, validate the password and set the
privledge.

OleDbCommand oMyCommand = new OleDbCommand(SQ L,
objConnection);
Reader = oMyCommand.Exec uteReader();

if (Reader.HasRows )
{
// Login is good here
MessageBox.Show ("Login is good");
Reader.Read();
Privelege = Reader.GetInt32 (3);
}
else
{
MessageBox.Show ("Login is bad");
}
}
finally
{
objConnection.C lose();
//Reader.Close();
}
}

The docs said to ensure I closed the reader but the compiler complained
about it...Not sure why.

Aug 18 '06 #4
Close the reader before you close the connection.

What you have done is used ADO.NET, but instead of SQL server
(System.Data.Sq lClient) you have used OleDb for Access
(System.Data.Ol eDb).
There is also: (System.Data.Or acleClient) and (System.Data.Od bc).
They all have Data readers, data connections, data adapters and command
objects, and they all work pretty much the same way, just differrent
connection strings of course.

Aug 18 '06 #5
Some security advice;

A: don't ever store passwords (even cyphered) unless you **really** nead to.
Perhaps hash them and compare hashes... and use a known hash (MD5 or
similar), not the CLR GetHashCode(), as that is implementation specific.

B: don't use string concatenation to place parareters into a SQL string -
you should be using the parameters collection instead (along with whichever
syntax is suitable in your SQL, for instance "?" or "@SomeParam " etc - refer
to documentation).

Firstly, you will run into trouble with the O'Neil's of this world. More
importantly, the reason for this is the simple trick of SQL-injection: for
instance, I could enter (as my user id on the form):
Fred' SELECT * FROM sysobjects --

or about 1000 other things (DROP TABLE... SELECT username, password...); you
can waste a lot of time trying to protect yourself by escaping characters
such as quotes, but the parameters approach deals with it all *much* more
efficiently, robustly and safely.

Best of luck,

Marc
Aug 18 '06 #6
Thanks a ton guys. This is very helpful. I am going to get SQL
express installed and setup a stored proc for the login stuff using
parms. My inital code was just to see if I could connect to a DB and
do something. Is there a standard algorythm for hashing other then the
CLI one?

Aug 18 '06 #7

heddy wrote:
Thanks a ton guys. This is very helpful. I am going to get SQL
express installed and setup a stored proc for the login stuff using
parms. My inital code was just to see if I could connect to a DB and
do something. Is there a standard algorythm for hashing other then the
CLI one?
Also, I need to have an object stay in scope throughout my application.
Should I instantiate the object in main to do this?

Aug 18 '06 #8
As for the security concern, I switched the login to use SQL Server
auth like this:

private void btnSubmit_Click (object sender, EventArgs e)
{
if (this.txtPassWd .Text.Length < 1 ||
this.txtUserID. Text.Length < 1)
{
MessageBox.Show ("You MUST fill both fields in!");
return;
}

SqlConnection Conn;
SqlDataReader reader = null;

Conn = new SqlConnection(" user id=" + this.txtUserID. Text +
";" +
"password=" +
this.txtPassWd. Text + ";" +
"server=MIKIE\\ SQLEXPRESS;" +
"database=M edia Manager;" +
"connection timeout=30");
try
{
Conn.Open();
}
catch
{
MessageBox.Show ("Login Failed for user: " +
this.txtUserID. Text);
return;
}

try
{
SqlCommand cmd = new SqlCommand("spG etAuthority",
Conn);
cmd.CommandType = CommandType.Sto redProcedure;
cmd.Parameters. Add(new SqlParameter("@ UserName",
this.txtUserID. Text));
reader = cmd.ExecuteRead er();

if (reader.HasRows )
{
// Login is good here
reader.Read();
oLocalUser.iAut hority = reader.GetInt32 (0);
oLocalUser.bLog gedIn = true;
MessageBox.Show ("Login is good for User: " +
this.txtUserID. Text + " Auth code = " +
oLocalUser.iAut hority.ToString ());

}
else
{
MessageBox.Show ("Login Failed");
}
}
finally
{
reader.Close();
Conn.Close();

}

}

Aug 18 '06 #9
And for my next question...

After my login form has finished it's processing (Login.frm), I do the
following to load the next form:

ProjectManager formProjects = new
ProjectManager( oLocalUser);
formProjects.Sh ow();
formProjects.Br ingToFront();
MessageBox.Show (this.Name);
this.Hide();
this.SendToBack ();

This all works wonderfully well. But, on the Projects form, when the
user exits the form, I need to show the Login form again. If I try to
reference the Login object, I do not get methods for show etc. How do
I reference back to the Login form so that I can show it again?

Thanks!

Aug 18 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3101
by: Mohammed Mazid | last post by:
Can anyone please help me on how to move to the next and previous question? Here is a snippet of my code: Private Sub cmdNext_Click() End Sub Private Sub cmdPrevious_Click() showrecord
3
5045
by: Stevey | last post by:
I have the following XML file... <?xml version="1.0"?> <animals> <animal> <name>Tiger</name> <questions> <question index="0">true</question> <question index="1">true</question> </questions>
7
2668
by: nospam | last post by:
Ok, 3rd or is it the 4th time I have asked this question on Partial Types, so, since it seems to me that Partial Types is still in the design or development stages at Microsoft, I am going to ask it differently. FOUR QUESTIONS: The background: I got three (3) files
3
3096
by: Ekqvist Marko | last post by:
Hi, I have one Access database table including questions and answers. Now I need to give answer id automatically to questionID column. But I don't know how it is best (fastest) to do? table before rowID answID qryrow questionID datafield 1591 12 06e 06e 06e question 1593 12 06f 06f 06f question 1594 12 answer to the question 06f
10
3444
by: glenn | last post by:
I am use to programming in php and the way session and post vars are past from fields on one page through to the post page automatically where I can get to their values easily to write to a database or continue to process on to the next page. I am now trying to learn ASP to see if we can replace some of our applications that were written in php with an ASP alternative. However, after doing many searches on google and reading a couple...
10
3744
by: Rider | last post by:
Hi, simple(?) question about asp.net configuration.. I've installed ASP.NET 2.0 QuickStart Sample successfully. But, When I'm first start application the follow message shown. ========= Server Error in '/QuickStartv20' Application. -------------------------------------------------------------------------------- Configuration Error Description: An error occurred during the processing of a configuration file
53
4100
by: Jeff | last post by:
In the function below, can size ever be 0 (zero)? char *clc_strdup(const char * CLC_RESTRICT s) { size_t size; char *p; clc_assert_not_null(clc_strdup, s); size = strlen(s) + 1;
56
4811
by: spibou | last post by:
In the statement "a *= expression" is expression assumed to be parenthesized ? For example if I write "a *= b+c" is this the same as "a = a * (b+c)" or "a = a * b+c" ?
2
4288
by: Allan Ebdrup | last post by:
Hi, I'm trying to render a Matrix question in my ASP.Net 2.0 page, A matrix question is a question where you have several options that can all be rated according to several possible ratings (from less to more for example). I have a question object that has two properties that contain the collections Options and Ratings. now I want this kind of layout: --- Rating1 Rating2 Rating3 Option 1 () () ...
3
2558
by: Zhang Weiwu | last post by:
Hello! I wrote this: ..required-question p:after { content: "*"; } Corresponding HTML: <div class="required-question"><p>Question Text</p><input /></div> <div class="not-required-question"><p>Question Text</p><input /></div>
0
9715
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10600
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10354
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10097
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9175
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6867
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3835
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3002
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.