代码改变世界

使用对象操作数据库

2012-05-13 13:48  RuMing  阅读(182)  评论(0编辑  收藏  举报

配置文件内容:

<connectionStrings>
        <add name="StudentInfoConnectionString" connectionString="Data Source=TANGPRO;Initial Catalog=StudentInfo;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>

  

代码页内容:

//调用配置文件中的连接对象
        string constr = System.Configuration.ConfigurationManager.ConnectionStrings["StudentInfoConnectionString"].ConnectionString;

        //建立连接
        using(SqlConnection conn = new SqlConnection(constr))
        {
            //打开连接
            conn.Open();
//命令 SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.Text; cmd.CommandText = "select no as 学号,name as姓名, gender as 性别, birthday as 出生日期 from student";
//数据集 SqlDataReader reader = cmd.ExecuteReader();
//数据集赋给显示控件 GridView1.DataSource = reader; GridView1.DataBind();
//最后记得关闭连接 conn.Close(); }

  

 

法二:

 //调用连接字符串
        string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["StudentInfoConnectionString"].ConnectionString;

        //建立连接对象
        SqlConnection conn = new SqlConnection();

        //打开连接
        conn.Open();

        //sql语句
        string strSql = "select no as 学号,name as姓名, gender as 性别, birthday as 出生日期 from student";

        //操作对象
        SqlCommand cmd = new SqlCommand(strSql, conn); //注意后面需要加上  操作语句 + 连接对象

        //数据集
        SqlDataReader reader = cmd.ExecuteReader();

        //显示数据
        GridView1.DataSource = reader;
        GridView1.DataBind();

        //关闭连接
        conn.Close();

  

 

向数据库中插入数据

string orderID = TextBox1.Text;
        string orderNAME = TextBox2.Text;

        string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["NewTestConnectionString"].ConnectionString;

        SqlConnection conn = new SqlConnection(conStr);
        conn.Open();

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into OrderTest(orderId,orderName) values('" + orderID + "','" + orderNAME + "')";//注意格式

        cmd.ExecuteNonQuery();//用于执行不返回结果,eg:  插入,删除,更像操作

        Label1.Text = "信息录入完成";

        conn.Close();