首页 > 编程 > C# > 正文

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

2020-01-24 02:43:52
字体:
来源:转载
供稿:网友
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("执行完成");
        }
    }
}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表