使用对象操作数据库

配置文件内容:

<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();

  

转载于:https://www.cnblogs.com/fromcuit/archive/2012/05/13/2498076.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值