asp.net 如何链接sql server2012数据库

2014-09-09 00:00:00 by 【6yang】, 323 visits, 收藏 | 返回
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text.RegularExpressions;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)//fsdafd
        {
            string strConn, strSQL;
            // Eg.1
            string connectionString = @"data source=.SQLEXPRESS;initial catalog=test;persist security info=True;user id=sa;password=123456";
           //SqlConnection conn = new SqlConnection(@"server=.SQLEXPRESS;database=test;uid=sa;pwd=123456");
            SqlConnection myConnection = new SqlConnection(connectionString);
            SqlCommand cmd = myConnection.CreateCommand();
            cmd.CommandText = "select * from myuser"; //这里不能用user哦,user是关键字,折腾了好久,才知道。初学啊
            myConnection.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            do
            {
                while(reader.Read())
                {
                    Response.Write(reader[1]);
                    //Response.Write(String.Format("{0}, {1}", reader[0], reader[1]));
                }
            } while (reader.NextResult());
           
            reader.Close(); //关闭只读、向前数据集
            myConnection.Close(); //关闭连接


            //Eg.2
            //SqlConnection conn = new SqlConnection();
            //conn.ConnectionString = @"data source=JACK-PCSQLEXPRESS;initial catalog=test;persist security info=True;user id=sa;password=123456";
            //SqlCommand cmd = new SqlCommand();
            //cmd.Connection = conn;
            //conn.Open();
            //Response.Write(conn.State);


            //使用无参数构造函数
           // strSQL = "SELECT * FROM user";
            //while (reader.Read())
            //{
            //   // Response.Write(String.Format("{0}, {1}", reader[0], reader[1]));
            //  //  Response.Write("test");
            //}
           
        }
    }
}
分享到:
share

    图片原图

    loading

    loading