simple question

B

Brian Henry

I have a sqlserver database called headlines

it has this format

ID | headline | text | date | link

i want to print out in a console the 1st item in this table that is in
ascendeing order based on the date. I am a databound person that has no idea
how to read data out of a table row by row. can someone help me with this? i
know how to do it in php with mysql by reading it into an array but .NET is
a lot diffrent then that. thanks
 
J

Joseph Hanna

Hi Brian,

You can still build an array of Data Rows using the SELECT method of a Data Table.

Try this...

'=======================================================

'Assuming you have already created a Connection, Data Adapter and Generated a Dataset in the
'Windows Form Designer or Component. This will provide you with a Strongly Typed Dataset.
'
'SqlConnection1 = Connection Object for your SQL Database
'SqlDataAdapter1 = Data Adapter Object for Table "headlines"
'DataSet11 = DataSet Object that was generated from the above Connection and Data Adapter
'

'Retrieve the records from the RDBMS into the DataSet
SqlDataAdapter1 .Fill(DataSet11)

'Return a Reference to the newly populated Data Table in DataSet11
Dim dt as DataTable = DataSet11.Headlines

'Return an Array of Generic Data Rows in Date Sequence (Row 1 is in element 0)
Dim drGenericArray() As DataRow = dt.Select(Nothing, "date_field")

'***********************************************************
'Method Number 1: Reference Generic Data Row Array directly
'***********************************************************

MessageBox.Show(drGenericArray(0)("id").ToString _
& vbCrLf & drGenericArray(0)("headline_field").ToString _
& vbCrLf & drGenericArray(0)("text_field").ToString _
& vbCrLf & drGenericArray(0)("date_field").ToString _
& vbCrLf & drGenericArray(0)("link_field").ToString, _
"First Row from Headlines (Method 1)")

'**************************************************************************************************
'Method Number 2: Much clearer for coding and you can use Intellisense because it is Strongly Typed
' Declare a variable of Type Dataset1.HeadlinesRow and assign the 1st element to it '
'**************************************************************************************************

'Declare the Strongly Typed Data Row
Dim dr As DataSet1.HeadLinesRow

'Convert First Element of Generic Data Row Type into HeadlinesRow Type
dr = CType(drGenericArray(0), DataSet1.HeadLinesRow)

MessageBox.Show(dr.ID _
& vbCrLf & dr.headline_field _
& vbCrLf & dr.text_field _
& vbCrLf & dr.date_field _
& vbCrLf & dr.link_field, _
"First Row from Headlines (Method 2)")

'=======================================================

Regards,
Joe

--

Joe Hanna
Advanced Software Engineering
joe.hanna_AT_advancedsoftware_DOT_net_DOT_au
 
P

Pete Wright

Ok, let's keep this nice and simple ;)

Before you go anywhere, you are going to need to add a reference to
System.Data.Sqlclient to your code. I'll assume that you're working with C#
in the example code that comes later.

Now, to actually get data out of the database, the first thing that you are
going to need to do is create a connection (since you need to connect, to
grab stuff). That's the job of a SqlConnection object. When you create it
you need to tell it the data source (which computer you want to talk to),
the initial catalog (database) that you want data from, and the security
model you want to use. The last bit can be tricky, but it's not. If you are
using Windows Authentication (i.e the database knows who you are from your
Windows log in information), then the security model is called SSPI.
However, if you need to log into the database, then you need to provide a
user name and password, and that's the method I'll use in the code in a bit.

Having got your connection, you can create a command to get the data. It's
actually a type of object called a SqlCommand, and it does nothing more than
provide you with a way to run commands against the database. In your case,
you want to select everything from the Headlines table in your test database
(so Select * from Headlines). When you create the command, you need to tell
it the SQL statement or stored procedure you want to run, and the connection
you want to use.

So far so good. Next step, open the connection, then tell the command to
ExecuteReader. What this does it run the command give you a Data Reader, a
simple data access object that lets you read the data returned from the
database in a forward only manner.

Now all you need to do is iterate through the rows of the database, and
print the values of each and every column.

When you're done, close the connection down and you're all set.

Here's the code (I'm actually using a table called Customers in the
Northwind database, but the principles are the same )
Bear in mind also that there are simpler ways of doing this (as in less
typing), and I would thoroughly recommend you take a look at a good ADO.NET
book, and also Microsoft's wonderfully useful Data Access Application Block
(search for it on MSDN).

using System;

using System.Data;

using System.Data.SqlClient;



namespace Simplereader

{

/// <summary>

/// Summary description for Class1.

/// </summary>

class Class1

{

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main(string[] args)

{

SqlConnection myConnection = new SqlConnection (

"Data Source=localhost;Initial Catalog=Northwind;" +

"Integrated Security=False;User ID=sa;Password=NewY0rk" );


SqlCommand myCommand = new SqlCommand(

"SELECT * FROM customers", myConnection );

myConnection.Open();

SqlDataReader myReader = myCommand.ExecuteReader();


while ( myReader.Read() )

{

for ( int i = 0 ; i < myReader.FieldCount ; i ++ )

{

System.Console.Write( myReader.GetValue(i).ToString() + " " );

}

System.Console.WriteLine();

}

myConnection.Close();

System.Console.WriteLine("All done - hit return to exit");

System.Console.ReadLine();

}

}

}



have fun

--
Peter Wright
Author of ADO.NET Novice To Pro, from Apress Inc.


_____________________________
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top