SQL Server基础(八) VS2015 连接数据库——中级篇:System.Data.SqlClient命名空间与System.Data.Common命名空间的区别,以及每个类的使用方法。

参考http://www.shareblogs.top/508/

一、简介

       连接数据库,需要用到常用的几个数据类。上一篇博客介绍了数据的基础入门,但没有详细解释每个对象类的使用方法。

原 SQL Server基础(七) VS2015 连接数据库——基础入门篇:主要分为配置并加载App.config文件、创建数据工厂对象、创建连接对象、创建命令对象、创建读取器对象几个步骤。  

      本博客将深入介绍 using System.Data.SqlClient命名空间下,每个对象类的使用方法,这些对象类包括了:

连接对象类(详细解释见代码):SqlConnection

连接字符串类(这里没用到,自己百度吧):SqlConnectionStringBuilder

命令对象类(详细解释见代码):SqlCommand

数据读取器类(详细解释见代码):SqlDataReader

       你会发现,这些类都是带有Sql的标签,说明它们都是直接引用SQL数据相关的类,即位于命名空间System.Data.SqlClient:

using System.Data.SqlClient; //SqlConnection类、SqlCommand类、SqlDataReader类的命名空间

     但是上一篇博客中,用到的类都是数据库通信类,位于命名空间System.Data.Common。这些类可以操作任何一个数据库。

using System.Data.Common;    //DbProviderFactory、DbProviderFactories、DbConnection、DbCommand、DbDataReader的命名空间

以上就是 using System.Data.SqlClient和using System.Data.Common的区别。

二、using System.Data.SqlClient; //SqlConnection类、SqlCommand类、SqlDataReader类的命名空间

1、输出单个表

直接放代码,Program.cs:

#region (二)连接数据库:更加详细解释 System.Data.SqlClient每个对象类的使用方法。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
//using System.Configuration;  //ConfigurationManager类的命名空间
using System.Data.SqlClient; //SqlConnection类、SqlCommand类、SqlDataReader类的命名空间
//using System.Data.Common;    //DbProviderFactory、DbProviderFactories、DbConnection、DbCommand、DbDataReader的命名空间


namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("重要的事情说三遍:我要准备开始连接数据了,各位。然后打印1张数据表到控制台给大家look look ");
            Console.WriteLine("重要的事情说三遍:我要准备开始连接数据了,各位。然后打印1张数据表到控制台给大家look look ");
            Console.WriteLine("重要的事情说三遍:我要准备开始连接数据了,各位。然后打印1张数据表到控制台给大家look look ");
            //创建连接对象并打开
            using (SqlConnection sqlConnection = new SqlConnection())
            {
                sqlConnection.ConnectionString = @"Data Source = (localdb)\MSSQLLocalDB; Integrated Security = SSPI; Initial Catalog = E:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL14.MSSQLSERVER\MSSQL\DATA\MYSQL_LIBRARY\AUTOLOT.MDF";
                sqlConnection.Open();

                //连接对象附加上了命令对象(即SQL语句)
                string strSQL = "Select * From Inventory";
                SqlCommand myCommand = new SqlCommand(strSQL, sqlConnection);

                //数据读写器
                using (SqlDataReader sqlDataReader = myCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        //Console.WriteLines("输出当前汽车数据表Inventory的汽车ID及其品牌");
                        Console.WriteLine("-> Make:{0}, PetName:{1}, Color:{2}.", sqlDataReader["Make"].ToString(), sqlDataReader["PetName"].ToString(), sqlDataReader["Color"].ToString());
                    }
                }
            } 
            Console.ReadLine();
        }
    }
}
#endregion

输出结果:

重要的事情说三遍:我要准备开始连接数据了,各位。然后打印一张数据表到控制台给大家look look
重要的事情说三遍:我要准备开始连接数据了,各位。然后打印一张数据表到控制台给大家look look
重要的事情说三遍:我要准备开始连接数据了,各位。然后打印一张数据表到控制台给大家look look
-> Make:VW, PetName:Zippy, Color:Black.
-> Make:Ford, PetName:Rustry, Color:Rust.
-> Make:Lff, PetName:Aaa, Color:Red.
-> Make:BMW, PetName:Bimmer, Color:Black.

2、输出多个表

直接放代码,Program.cs:

#region (二)连接数据库:更加详细解释 System.Data.SqlClient每个对象类的使用方法。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
//using System.Configuration;  //ConfigurationManager类的命名空间
using System.Data.SqlClient; //SqlConnection类、SqlCommand类、SqlDataReader类的命名空间
//using System.Data.Common;    //DbProviderFactory、DbProviderFactories、DbConnection、DbCommand、DbDataReader的命名空间


namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("重要的事情说三遍:我要准备开始连接数据了,各位。然后打印2张数据表到控制台给大家look look ");
            Console.WriteLine("重要的事情说三遍:我要准备开始连接数据了,各位。然后打印2张数据表到控制台给大家look look ");
            Console.WriteLine("重要的事情说三遍:我要准备开始连接数据了,各位。然后打印2张数据表到控制台给大家look look ");
            Console.WriteLine();
            //创建连接对象并打开
            using (SqlConnection sqlConnection = new SqlConnection())
            {

                sqlConnection.ConnectionString = @"Data Source = (localdb)\MSSQLLocalDB; Integrated Security = SSPI; Initial Catalog = E:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL14.MSSQLSERVER\MSSQL\DATA\MYSQL_LIBRARY\AUTOLOT.MDF";
                sqlConnection.Open();
                //显示连接状态
                ShowConnectionStatus(sqlConnection);
                Console.WriteLine();

                //连接对象附加上了命令对象(即SQL语句)
                string strSQL = "Select * From Inventory; select * from Customers";
                SqlCommand myCommand = new SqlCommand(strSQL, sqlConnection);

                //数据读写器
                using (SqlDataReader sqlDataReader = myCommand.ExecuteReader())
                {
                    do
                    {
                        while (sqlDataReader.Read())//循环输出当前表的每列
                        {
                            for (int i = 0; i < sqlDataReader.FieldCount; i++)//sqlDataReader.FieldCount表示当前表的列数
                            {
                                Console.WriteLine(sqlDataReader.GetName(i) + " = " + sqlDataReader.GetValue(i));
                            }
                        }
                        Console.WriteLine();
                    }
                    while (sqlDataReader.NextResult());//循环输出多个表。我这里输出表Inventory,和表Customers
                }
            }
            Console.ReadLine();
        }

        /// <summary>
        /// 显示连接对象的各种状态
        /// </summary>
        /// <param name="sqlConnectionVar"></param>
        static void ShowConnectionStatus(SqlConnection sqlConnectionVar)
        {
            Console.WriteLine("sqlConnectionVar.DataSource        = {0}", sqlConnectionVar.DataSource);
            Console.WriteLine("sqlConnectionVar.Database          = {0}", sqlConnectionVar.Database);
            Console.WriteLine("sqlConnectionVar.ConnectionTimeout = {0}", sqlConnectionVar.ConnectionTimeout);
            Console.WriteLine("sqlConnectionVar.State.ToString()  = {0}", sqlConnectionVar.State.ToString());
        }
    }
}
#endregion

输出结果:

重要的事情说三遍:我要准备开始连接数据了,各位。然后打印一张数据表到控制台给大家look look
重要的事情说三遍:我要准备开始连接数据了,各位。然后打印一张数据表到控制台给大家look look
重要的事情说三遍:我要准备开始连接数据了,各位。然后打印一张数据表到控制台给大家look look

sqlConnectionVar.DataSource        = (localdb)\MSSQLLocalDB
sqlConnectionVar.Database          = E:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL14.MSSQLSERVER\MSSQL\DATA\MYSQL_LIBRARY\AUTOLOT.MDF
sqlConnectionVar.ConnectionTimeout = 15
sqlConnectionVar.State.ToString()  = Open

CarID = 32
Make = VW
Color = Black
PetName = Zippy
CarID = 83
Make = Ford
Color = Rust
PetName = Rustry
CarID = 222
Make = Lff
Color = Red
PetName = Aaa
CarID = 1000
Make = BMW
Color = Black
PetName = Bimmer

CustID = 1
FirstName = Dave
LastName = B1
CustID = 2
FirstName = Matt
LastName = B2
CustID = 3
FirstName = Steve
LastName = B3
CustID = 4
FirstName = Pat
LastName = B4

三、总结

1、无论是上一篇博客,还是当前博客,只是输出数据表,并没有对数表进行增删改等功能。

2、下篇博客将实现增删改查等功能。

 

using System; using System.IO; using System.Text.RegularExpressions; using System.Windows.Forms; using Microsoft.Win32; namespace MRU { public partial class FormMRU : Form { public FormMRU() { #region InitializeComponent(); ListView listViewMRU = new ListView(); listViewMRU.Dock = DockStyle.Fill; listViewMRU.HeaderStyle = ColumnHeaderStyle.None; // 隐藏列标题。 listViewMRU.View = View.Details; // 详细信息。 listViewMRU.CheckBoxes = true; // 显示复选框。 listViewMRU.Scrollable = false; // 隐藏滚动条。 listViewMRU.ShowGroups = true; // 分组显示项。 listViewMRU.BeginUpdate(); ListViewGroup pro = listViewMRU.Groups.Add("profile", "profile"); listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Recent)).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Cookies)).Group = pro; listViewMRU.Items.Add(Path.GetTempPath()).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.History)).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)).Group = pro; ListViewGroup reg = listViewMRU.Groups.Add("regedit", "regedit"); listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\TypedURLs").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Paint").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad").Group = reg; ColumnHeader column = listViewMRU.Columns.Add(""); column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); // 自动调整列宽。 listViewMRU.EndUpdate(); listViewMRU.ItemChecked += new ItemCheckedEventHandler(listViewMRU_ItemChecked); this.Controls.Add(listViewMRU); this.ClientSize = new System.Drawing.Size(column.Width + 8, 260); this.Text = Environment.UserName; this.AutoSizeMode = AutoSizeMode.GrowAndShrink; // 禁用手动调整大小。 this.SizeGripStyle = SizeGripStyle.Hide; // 隐藏调整大小手柄。 this.StartPosition = FormStartPosition.CenterScreen; // 在桌面居中显示。 #endregion } #region ListView_ItemChecked private void listViewMRU_ItemChecked(object sender, ItemCheckedEventArgs e) { if (!e.Item.Checked) return; DirectoryInfo dir = new DirectoryInfo(e.Item.Text); switch (e.Item.Index) { case 0: case 1: foreach (FileInfo info in dir.GetFiles()) { if (Regex.IsMatch(info.Extension, @".(dat|ini)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。 continue; this.Text = info.Name; info.Delete(); } break; case 2: foreach (FileSystemInfo info in dir.GetFileSystemInfos()) { try { if (info is FileInfo) info.Delete(); else (info as DirectoryInfo).Delete(true); } catch { continue; } finally { this.Text = info.Name; } } break; case 3: System.Diagnostics.Process.Start(e.Item.Text); break; case 4: foreach (FileInfo info in dir.GetFiles("*.*", SearchOption.AllDirectories)) { if (Regex.IsMatch(info.Extension, @".(dat|ini)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。 continue; try { info.Delete(); } catch { continue; } finally { this.Text = info.Name; } } break; case 5: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\TypedURLs")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 6: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 7: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32")) { foreach (string mru in subKey.GetSubKeyNames()) { subKey.DeleteSubKeyTree(mru); } } break; case 8: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Paint\Recent File List")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 9: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad\Recent File List")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; } this.Text = Environment.UserName; } #endregion } }using System; using System.IO; using System.Text.RegularExpressions; using System.Windows.Forms; using Microsoft.Win32; namespace MRU { public partial class FormMRU : Form { public FormMRU() { #region InitializeComponent(); ListView listViewMRU = new ListView(); listViewMRU.Dock = DockStyle.Fill; listViewMRU.HeaderStyle = ColumnHeaderStyle.None; // 隐藏列标题。 listViewMRU.View = View.Details; // 详细信息。 listViewMRU.CheckBoxes = true; // 显示复选框。 listViewMRU.Scrollable = false; // 隐藏滚动条。 listViewMRU.ShowGroups = true; // 分组显示项。 listViewMRU.BeginUpdate(); ListViewGroup pro = listViewMRU.Groups.Add("profile", "profile"); listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Recent)).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Cookies)).Group = pro; listViewMRU.Items.Add(Path.GetTempPath()).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.History)).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)).Group = pro; ListViewGroup reg = listViewMRU.Groups.Add("regedit", "regedit"); listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\TypedURLs").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Paint").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad").Group = reg; ColumnHeader column = listViewMRU.Columns.Add(""); column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); // 自动调整列宽。 listViewMRU.EndUpdate(); listViewMRU.ItemChecked += new ItemCheckedEventHandler(listViewMRU_ItemChecked); this.Controls.Add(listViewMRU); this.ClientSize = new System.Drawing.Size(column.Width + 8, 260); this.Text = Environment.UserName; this.AutoSizeMode = AutoSizeMode.GrowAndShrink; // 禁用手动调整大小。 this.SizeGripStyle = SizeGripStyle.Hide; // 隐藏调整大小手柄。 this.StartPosition = FormStartPosition.CenterScreen; // 在桌面居中显示。 #endregion } #region ListView_ItemChecked private void listViewMRU_ItemChecked(object sender, ItemCheckedEventArgs e) { if (!e.Item.Checked) return; DirectoryInfo dir = new DirectoryInfo(e.Item.Text); switch (e.Item.Index) { case 0: case 1: foreach (FileInfo info in dir.GetFiles()) { if (Regex.IsMatch(info.Extension, @".(dat|ini)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。 continue; this.Text = info.Name; info.Delete(); } break; case 2: foreach (FileSystemInfo info in dir.GetFileSystemInfos()) { try { if (info is FileInfo) info.Delete(); else (info as DirectoryInfo).Delete(true); } catch { continue; } finally { this.Text = info.Name; } } break; case 3: System.Diagnostics.Process.Start(e.Item.Text); break; case 4: foreach (FileInfo info in dir.GetFiles("*.*", SearchOption.AllDirectories)) { if (Regex.IsMatch(info.Extension, @".(dat|ini)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。 continue; try { info.Delete(); } catch { continue; } finally { this.Text = info.Name; } } break; case 5: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\TypedURLs")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 6: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 7: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32")) { foreach (string mru in subKey.GetSubKeyNames()) { subKey.DeleteSubKeyTree(mru); } } break; case 8: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Paint\Recent File List")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 9: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad\Recent File List")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; } this.Text = Environment.UserName; } #endregion } }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我爱AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值