Web in Visual Studio connect to SQL server

基础配置 http://blog.csdn.net/kof820/article/details/7040964

连接案例 http://jingyan.baidu.com/article/3ea51489e562bb52e61bbab0.html

 

1. 新建数据库

  数据库School   表Student

    

 

2. Visual Studio

      New -- > Web ---> ASP.NET Empty Web

  Tools---> Connect to database

    

  Test Connection ---> OK

    

  Copy to the code

    

  Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.SqlClient;

public partial class SQLTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
     //Paste Here!!!
string strSQLConnect = "Data Source=MIRROR\\MIRRORSQLSERVER;Initial Catalog=School;User ID=sa;Password=****"; SqlConnection mySqlConnection = new SqlConnection(strSQLConnect); using (mySqlConnection) { mySqlConnection.Open(); Label1.Text = "<b>mySqlConnection/ConnectionString:<b>" + mySqlConnection.ConnectionString + "<br>"; Label1.Text += "<b>mySqlConnection/ConnectionTimeout:<b>" + mySqlConnection.ConnectionTimeout + "<br>"; Label1.Text += "<b>mySqlConnection/Database:<b>" + mySqlConnection.Database + "<br>"; Label1.Text += "<b>mySqlConnection/DataSource:<b>" + mySqlConnection.DataSource + "<br>"; Label1.Text += "<b>mySqlConnection/PacketSize:<b>" + mySqlConnection.PacketSize + "<br>"; Label1.Text += "<b>mySqlConnection/ServerVersion:<b>" + mySqlConnection.ServerVersion + "<br>"; Label1.Text += "<b>mySqlConnection/State:<b>" + mySqlConnection.State + "<br>";

        string ss = String.Format("Insert into Student(SName,Phone,Address)values('{0}','{1}','{2}')", "Angela", "1234567890", "Chengdu");
        SqlCommand myAddCommand = new SqlCommand(ss, mySqlConnection);
        myAddCommand.ExecuteNonQuery();

        //SqlCommand myAddCommand = new SqlCommand("Insert into Student(SName,Phone,Address)values('Angela','12345678900','Chengdu')",mySqlConnection);

        //myAddCommand.ExecuteNonQuery();



            SqlCommand myReadCommand = new SqlCommand("Select * from Student",mySqlConnection);
            SqlDataReader myReader = myReadCommand.ExecuteReader();

            //FieldCount: get the number of columns in the current row
            for (int i = 0; i < myReader.FieldCount; i++)
            {
                Label2.Text += myReader.GetName(i) + "<br>";
            }

            while (myReader.Read())
            {
                for (int j = 0; j < myReader.FieldCount; j++)
                {
                    Label3.Text += myReader[j].ToString();
                }
            }
        }
        //out of the using{} is the state of Connection closed.
        Label4.Text = mySqlConnection.State.ToString();
    }
}

 

posted @ 2014-12-09 14:34  Mirrorhanman  阅读(439)  评论(0编辑  收藏  举报