开发者

display information from sql db to asp.net webpage

I think what I need is simple but I can't achieve it through asp.net because I am a total beginner.

What I need is to display a field from sql db table to my webpage like this example:

Account 开发者_JAVA技巧Information 

    Your Name is: <Retrieve it from db>
    Your Email is: <Retrieve it from db>

How should I do that ?

I already have table members.

I need to do this with c# , I am using Visual Studio Web Express 2010


First step is add the SQL Client namespace:

using System.Data.SqlClient;

DB Connection

Then we create a SqlConnection and specifying the connection string.

SqlConnection myConnection = new SqlConnection("user id=username;" + 
                                       "password=password;server=serverurl;" + 
                                       "Trusted_Connection=yes;" + 
                                       "database=database; " + 
                                       "connection timeout=30");

This is the last part of getting connected and is simply executed by the following (remember to make sure your connection has a connection string first):

try
{
    myConnection.Open();
}
catch(Exception e)
{
    Console.WriteLine(e.ToString());
}

SqlCommand

An SqlCommand needs at least two things to operate. A command string, and a connection. There are two ways to specify the connection, both are illustrated below:

SqlCommand  myCommand = new SqlCommand("Command String", myConnection);

// - or -

myCommand.Connection = myConnection;

The connection string can also be specified both ways using the SqlCommand.CommandText property. Now lets look at our first SqlCommand. To keep it simple it will be a simple INSERT command.

SqlCommand myCommand= new SqlCommand("INSERT INTO table (Column1, Column2) " +
                                     "Values ('string', 1)", myConnection);

// - or - 

    myCommand.CommandText = "INSERT INTO table (Column1, Column2) " + 
                            "Values ('string', 1)";

SqlDataReader

Not only do you need a data reader but you need a SqlCommand. The following code demonstrates how to set up and execute a simple reader:

try
{
    SqlDataReader myReader = null;
    SqlCommand    myCommand = new SqlCommand("select * from table", 
                                             myConnection);
    myReader = myCommand.ExecuteReader();
    while(myReader.Read())
    {
        Console.WriteLine(myReader["Column1"].ToString());
        Console.WriteLine(myReader["Column2"].ToString());
    }
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜