About connect SQL database using C#

  • Thread starter Thread starter Yiu
  • Start date Start date
Y

Yiu

i am the new guy for C#.
i want to ask how to connect to SQL server 2000 and select something from the table?
thx
 
Here's a quick example:

Dim cn As New SqlConnection("Data Source=AUG-SQLSRV;Integrated
Security=SSPI;Initial Catalog=JobTracking")

Dim cmd As New SqlCommand("SELECT * FROM vw_Log_Attempts", cn)

Dim da As New SqlDataAdapter(cmd)

Dim dtAttempt As New DataTable

Try

da.Fill(dtAttempt)
 
"Microsoft ADO.NET Core Reference" by David Sceppa (who participates in this
forum) is a fine book that covers much of the basics of using ADO.NET. I
think you are going to need to read this or something like it because just
answering your first question will not get you far in understanding ADO.NET
data access.

Tom
 
I second that...Sceppa's book as well as Bill Vaughn's ADO/ADO.NET Best
Practices have gotten me through every problem I've encountered and saved a
ton of trial-and-error time.
 
what is that mean Data Source=AUG-SQLSRV ?
no need to type username and password?
and how to use the result to get value to palce on the Label?
 
Aug-SqlSrv is an example of the name of a Database, if you are using
INtegrated Security and you have permissions, then no, you don't need
username and password, otherwise, yes you do.

As for the label, once you have your commandtext and connection ready to
go..myLabel.Text = cmd.ExecuteScalar (ExectueScalar will return only one
value).

HTH,
Bill
 
Oops, I had a VB project open so that's what I grabbed - not intentional
though.

SqlConnection cn = new SqlConnection("ConnectString");
SqlCommand cmd = new SqlCommand("SELECT LastName FROM WhateverTable WHERE
SomeValue = 'aasdfasdf'", cn)
if(cn.State != ConnectionState.Open){cn.Open();}
label.text = cmd.ExecuteScalar();

I didn't use SqlParameters b/c I didn't want to overcomplicate it , as soon
as you get this to work, check out using Parameters instead...

"SELECT LastName from WhateverTable Where SomeValue = @SomeValue", cn);
cmd.Parameters.Clear();
cmd.Parameters.Add("@SomeValue", SqlDbType.Varchar, 20).Value = "aasdfasdf";
 
Thanks for that, I've just ordered William Vaughan "examples and best
practices" from Amazon. There are loads of non-obvious pratfall savers in
Sceppa so hopefully there are a few different ones in Vaughan.

Tom
 
Back
Top