欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

adonet基础示例分享(adonet连接数据库)

程序员文章站 2023-12-19 18:42:22
adonet基础示例分享复制代码 代码如下:using system;using system.collections.generic;using system.linq;...
adonet基础示例分享
复制代码 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.windows;
using system.windows.controls;
using system.windows.data;
using system.windows.documents;
using system.windows.input;
using system.windows.media;
using system.windows.media.imaging;
using system.windows.navigation;
using system.windows.shapes;
using system.data.sqlclient;

namespace adonet基础 {
    /// <summary>
    /// window1.xaml 的交互逻辑
    /// </summary>
    public partial class window1 : window
    {
        public window1()
        {
            initializecomponent();
        }

        private void button1_click(object sender, routedeventargs e)
        {
            ////using() 自动关闭数据库,回收资源。
            ////sqlconnection为建立和数据库连接的对象。
            //using (sqlconnection conn = new sqlconnection("data source=.;initial catalog=myself;user id=sa;password=123;"))
            //{
            //    conn.open();//打开连接
            //    //通过连接,创建一个向数据库发命令的对象sqlcommand
            //    using (sqlcommand cmd = conn.createcommand())//释放资源。
            //    {
            //        //commandtext为要执行的sql的语句
            //        cmd.commandtext = "insert into student(学号,姓名) values(110,'张五')";
            //        //executenonquery一般用来执行update delete insert 语句。
            //        cmd.executenonquery();//执行上面的sql语句。
            //    }
            //}

            using (sqlconnection conn = new sqlconnection("data source=.;initial catalog=mytest;user id=sa;password=123;"))
            {
                conn.open();
                using (sqlcommand cmd = conn.createcommand())
                {
                    //cmd.commandtext = "select count(*) from student where 入学成绩<570";
                    //cmd.commandtext = "select count(*) from student where 入学成绩<570";
                    ////executescalar一般用来执行有且只有一行一列返回值的sql语句。
                    //int i = (int)cmd.executescalar();
                    //messagebox.show(i+"人成绩小于570分");
                    cmd.commandtext = "insert into t_student(name,age) output inserted.id values('张顾',18);";
                    long i = (long)cmd.executescalar();
                    messagebox.show("id为"+i);
                }
            }
            messagebox.show("执行完成");
        }
    }
}

上一篇:

下一篇: