ADO.NET學習(一)


一、ADO.NET簡介

ADO.NET可以看作是C#語言訪問數據庫的一種方式。編程語言編寫的程序需要數據庫的支持,那么怎樣才能讓他們建立連接呢?當然是ADO.NET

二、ADO.NET 整體流程

1)寫連接字符串

2)寫連接對象

3)寫sql語句

4)寫操作SQL語句的對象SqlCommand

5)打開數據庫

6)最后寫執行操作對象的方法:ExecuteNonQuery(),executescalar(),ExecuteReader()

其中還有寫小步驟,具體在案例里面顯示。(第四步和第五步可以互換)

三、連接字符串

如果想了解詳細的:https://www.cnblogs.com/shuibi/p/6566127.html

SQL SEVER

標准安全連接: 

Data Source=.;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;或者

Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;Trusted_Connection=False;

可信連接:

Data Source=192.168.0.4;Initial Catalog=MyDataBase;Integrated Security=True;或者

Server=ServerAddress;Database=MyDataBase;Trusted_Connection=True;

Access連接字符串

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\myDatabase.mdb;User Id=admin;Password=;

MySQL連接字符串

Server=myServerAddress;Database=myDatabase;Uid=myUsername;Pwd=myPassword;

DB2連接字符串

Server=myAddress:myPortNumber;Database=myDatabase;UID=myUsername;PWD=myPassword;

Oracle連接字符串

Data Source=TORCL;User Id=myUsername;Password=myPassword;

注意:如果你實在不知道怎么寫,也可以通過VS來獲取連接字符串

工具 >>>連接到數據庫

 

提前准備好數據庫,后面使用:
--創建數據庫
create database ExampleInfo
--創建學生表
create table StudentTable(
Sid int not null primary key identity,
Sname varchar(50),
Sage datetime,
Ssex nvarchar(10)
)
insert into StudentTable(Sname,Sage,Ssex) values ('王昭君',18,''),('貂蟬',18,''),('韓信',18,''),
('李白',20,''),('蔡文姬',19,''),('后裔',19,''),('伽羅',19,'')

--創建課程表
create table CourseTable(
Cid int not null primary key identity,
Cname varchar(50),
Tid int
)
insert into CourseTable(Cname,Tid) values ('語文',1),('數學',3),('英語',5),
('物理',4),('化學',6),('生物',5),('地理',2)

--創建教師表
create table TeacherTable(
Tid int not null primary key identity,
Tname varchar(50)
)

insert into TeacherTable(Tname) values ('諸葛亮'),('黃總'),('老夫子'),('墨子'),('女媧'),('伏羲')

--創建一張學生課程表
create table SCTable(
Sid int,
Cid int,
Score int,
foreign Key (Sid) REFERENCES StudentTable(Sid),
foreign Key (Cid) REFERENCES CourseTable(Cid)
)

insert into SCTable (Sid,Cid,Score) values (1,1,80),(1,2,89),(1,3,88),(1,4,87),(1,5,78),
(1,6,48),(1,7,87),(2,1,55),(2,2,77),(2,4,99),(2,5,89),(2,6,15),(3,1,88),(3,2,77),(3,3,78),(3,4,75),(3,5,67),
(3,6,89),(3,7,88),(4,1,78),(4,4,98),(4,5,89),(4,6,78),(4,7,79),(5,1,77),(5,2,85),(5,3,82),(5,5,76),
(5,6,95),(6,1,94),(6,4,48),(7,1,58),(7,2,88),(7,4,75),
(7,6,84),(7,7,99)

 

 

四、連接對象Connection

主要是用於連接到數據庫的

由於后面需要

Connection常用屬性:

  屬性 說明
ConncetionString 獲取或設置用於打開數據庫的字符串
ConnectioTimeout 獲取在嘗試建立連接時終止嘗試並生成錯誤之前所等待的時間
DataBase 獲取當前數據庫,或者連接打開后要使用的數據名稱
DataSource 獲取喲啊連接的數據庫服務器的名稱
State 數據庫連接狀態

 

 

 

 

 

 

 

Connection常用方法:

方法 說明
Open 打開數據庫連接
Close 關閉數據庫連接
Dispose 釋放Connection使用的所有資源

 

 

 

 

 

 

 

這是一個使用模板
//編寫連接字符串
String constr = "Data Source = .;Initial Catalog = ExampleInfo;Integrated Security = True"
//創建連接對象
using(SqlConnection conn = new Sqlnnection(Constr)){ // 當在某個代碼段中使用了類的實例,而希望無論因為什么原因,只要離開了這個代碼段就自動調用這個類實例的Dispose
//要達到這樣的目的,用try...catch來捕捉異常也是可以的,但用using也很方便。
   
//寫Sql語句 //創建command對象 //打開數據 //執行 }

五、Command

Command有四種:SqlCommand,OleDbCommand,OdbcCommand,OracleComman

具體看使用的是什么數據庫。

Command對象常用的屬性

屬性 說明
CommandType 獲取要執行命令的類型
CommandText 獲取或者設置要對數據源執行的SQL語句或存儲過程或表名
Conncetion 獲取或設置這個Command使用的Connection對象的名稱
Parameters 獲取Command對象需要使用的參數集合
Transaction 獲取或設置將在其中執行的SqlTransaction

 

 

 

 

 

 

 

 

 

 

 

 
         
這是一個使用模板
//
編寫連接字符串 String constr = "Data Source = .;Initial Catalog = ExampleInfo;Integrated Security = True" //創建連接對象 using(SqlConnection conn = new Sqlnnection(Constr)){ //寫Sql語句 string sql = "select * from StudentTable"; using(SqlCommand cmd = new Command(sql,conn)){ //打開數據 conn.Open(); //執行
        ....
} }

 Command對象常用的方法:

(一)ExecuteNonQuery

用於執行非select語句,比如增刪改,它會返回影響的行數

1.向數據庫中的StudentTable表中插入數據
using
System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace commandExecuteNonQuery { class Program { static void Main(string[] args) { //創建連接字符串 string constr = "Data Source =.;Initial Catalog = ExampleInfo;Integrated Security = True"; //創建連接對象 using(SqlConnection conn = new SqlConnection(constr)){ //床架sql語句 string sql = "insert into StudentTable (Sname,Sage,Ssex) values ('露娜',16,'女')"; //創建command對象 using (SqlCommand cmd = new SqlCommand(sql, conn)) { //打開數據庫 conn.Open(); //執行數據語句的command方法 int x = cmd.ExecuteNonQuery(); //返回的是受影響的行數 if (x > 0) { Console.WriteLine("插入成功"); }else{ Console.WriteLine("插入失敗"); } } } } } }

(二)ExecuteScalar

通常用來執行SELECT查詢命令,返回第一行第一列值,所以都是用來執行帶有Count() 或者是Sum()函數的數據庫SQL語句

1.返回數據庫表StudentTable的記錄條數
using
System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace commandExecuteNonQuery { class Program { static void Main(string[] args) { //創建連接字符串 string constr = "Data Source =.;Initial Catalog = ExampleInfo;Integrated Security = True"; //創建連接對象 using (SqlConnection conn = new SqlConnection(constr)) { //床架sql語句 string sql = "select Count(*) from StudentTable"; //創建command對象 using (SqlCommand cmd = new SqlCommand(sql, conn)) { //打開數據庫 conn.Open(); //執行數據語句的command方法 object x = cmd.ExecuteScalar(); Console.WriteLine(x); } } } } }

(三)ExecuteReader

由於ExecuteReader通常是和DataReader一起使用的,所以我就放到DataReader一起說

五、DataReader

是一個簡單的數據集

DataReader對象的常用屬性:

屬性 說明
Connection 獲取與DataReader關聯的Conncetion對象
HasRows 判斷數據庫中是否有數據
FieldCount   獲取當前行的列數
IsClosed 是否已關閉DataReader實例,是一個bool值
Item 獲取指定列的以本機的格式表示的值

 

 

 

 

 

 

 

 

 

 

DataReader對象的常用方法:

方法 說明
ISDBNull 獲取一個值,判斷是否是空值
Read 使DataReader對象指向下一條記錄
NextResult 使數據讀取器前進到下一個結果
Close 關閉DataReader
Get 用來讀取數據集的當前行的某一列的數據

 

 

 

 

 

 

 

 

 

這是一個使用模板
//
連接字符串 string constr = "data source =.;Initial catalog = StudentInfo;Integrated Security = True"; //創建連接對象 using (SqlConnection conn = new SqlConnection(str2)) { //sql語句 string sql = "select * from StudentTable"; //創建Command對象 using (SqlCommand comm = new SqlCommand(sql, conn)) {//打開數據庫 conn.Open(); //創建DataReader對象 using (SqlDataReader reader = comm.ExecuteReader()) { if (reader.HasRows) //如果有數據,一條一條去讀數據 { //reader.Read() 向后移動一條數據(因為默認指向-1,就是開始時候不指向任何數據),有數據就會返回true while (reader.Read()) { .......... } } } } }

 

//小案例:查詢返回表StudentTable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace commandExecuteNonQuery
{
    class Program
    {
        static void Main(string[] args)
        {
            //創建連接字符串
            string constr = "Data Source =.;Initial Catalog = ExampleInfo;Integrated Security = True";
            //創建連接對象
            using (SqlConnection conn = new SqlConnection(constr))
            {
                //床架sql語句
                string sql = "select * from StudentTable";
                //創建command對象
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    //打開數據庫
                    conn.Open();
                    //執行數據語句ExecuteReader()的方法
                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader.HasRows) {
                       while (reader.Read()) {
                            Console.Write(reader.GetInt32(0)  +  "             ");
                            Console.Write(reader.GetString(1) + "             ");
                            Console.Write(reader.GetInt32(2) + "             ");
                            Console.Write(reader.GetString(3) + "             ");
                            Console.WriteLine();
                        } } } } } } }

 

六、DataAdapter

 DataAdapter表示一組 SQL 命令和一個數據庫連接,它們用於填充 DataSet和更新數據源

DataAdapter的屬性:

屬性 說明
SelectCommand 引用從數據源中檢索行的Command對象
InsertCommand 引用將插入的行從DataSet寫入數據源的Command對象
UpdateCommand 引用將修改的行從DataSet寫入數據源的Command對象
DeleteCommand 引用從數據源中刪除行的Command對象

 

 

 

 

 

 

 

 

 

DataAdapter的方法:

方法 說明
Fill 使用SqlDataAdapter(或OleDbDataAdapter)的這個方法,從數據源增加或刷新行,並將這些行放到DataSet表中。Fill方法調用SelectCommand屬性所指定的SELECT語句
Update 使用DataAdapter對象的這個方法,將DataSet表的更改傳送到相應的數據源中。該方法為DataSet的DataTable中每一指定的行調用相應的INSERT、UPDATE或DELETE命令

 

 

 

 

 

 

案例、編寫一個小程序,創建一個窗體應用程序,然后在窗體應用程序中創建拖“DataGridView”和‘Button’控件。實現點擊‘button’控件就會在“DataGridView”中顯示

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DataAdpter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //創建連接字符串
            string constr = "Data Source =.;Initial Catalog = ExampleInfo;Integrated Security = True";
            //創建連接對象
            using (SqlConnection conn = new SqlConnection(constr))
            {
                //床架sql語句
                string sql = "select * from StudentTable";
                //創建command對象
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
            //創建一個DataTable對象 DataTable ds
= new DataTable(); using (SqlDataAdapter adapter = new SqlDataAdapter(sql, constr)) { //打開數據庫 conn.Open(); adapter.Fill(ds); }  
             //綁定dataGridView控件
this.dataGridView1.DataSource = ds; } } } } }
//上述的代碼中Datable可以改成DataSet  
private void button1_Click_1(object sender, EventArgs e) { //創建連接字符串 string constr = "Data Source =.;Initial Catalog = ExampleInfo;Integrated Security = True"; //創建連接對象 using (SqlConnection conn = new SqlConnection(constr)) { //床架sql語句 string sql = "select * from StudentTable"; //創建command對象 using (SqlCommand cmd = new SqlCommand(sql, conn)) { DataSet ds = new DataSet(); using (SqlDataAdapter adapter = new SqlDataAdapter(sql, constr)) { //打開數據庫 conn.Open(); adapter.Fill(ds); } this.dataGridView1.DataSource = ds.Tables[0]; } } }

六、封裝SqlHelper

 為什么要封裝成SqlHelper?

 如果不封裝的話,我們每寫一次查詢就要寫一次連接字符串,連接對象等等,如果一個程序當中有n個,就要寫n此。那么不如將其封裝起來,可以直接調用。我們只用提供sql語句和參數就可以了

封裝第一步:創建一個項目:窗體應用程序(由於我會直接在這里寫案例,所以就直接創建窗體),名稱:LoginInfo
封裝第二步:如下圖
封裝第二步驟,在App.config中添加如下代碼


懶人這里復制(還是要多多手打哦):
<configuration>
  <connectionStrings>
    <add name="mssqlsrever" connectionString="Data Source =.;Initial Catalog =ExampleInfo;Integrated Security = True"  />
  </connectionStrings>
封裝第三步:創建SqlHelper類

封裝第五步:上代碼
 
         
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace LoginInfo
{
   public class SqlHelper
    {//定義一個鏈接字符串
        //readOnly 修飾的變量,只能在初始話的時候賦值,以及在構造函數中賦值
        //讀取配置文件中的鏈接字符串
        private static readonly string constr = ConfigurationManager.ConnectionStrings["mssqlsrever"].ConnectionString;


        //執行增刪改的方法   ExecuteNonQuery   params SqlParameter[] paras 可能存在sql語句中帶有參數,那么需要把參數給加進去
        public static int ExecuteNonQuery(string sql, params SqlParameter[] paras)
        {
            using (SqlConnection conn = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    if (paras != null)
                    {
                        cmd.Parameters.AddRange(paras);
                    }
                    conn.Open();
                    return cmd.ExecuteNonQuery();

                }
            }
        }


        //執行查詢,返回單個值方法   ExecuteScalar
        public static object ExecuteScalar(string sql, params SqlParameter[] paras)
        {
            using (SqlConnection conn = new SqlConnection(constr))
            {
                using (SqlCommand comm = new SqlCommand(sql, conn))
                {
                    if (paras != null)
                    {
                        comm.Parameters.AddRange(paras);
                    }
                    conn.Open();
                    return comm.ExecuteScalar();
                }

            }

        }

        //執行查詢 返回多行多列的方法  ExecuteReader
        public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] paras)
        {
            using (SqlConnection conn = new SqlConnection(constr))
            {
                using (SqlCommand comm = new SqlCommand(sql, conn))
                {
                    if (paras != null)
                    {
                        comm.Parameters.AddRange(paras);
                    }
                    try
                    {
                        conn.Open();
                        return comm.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
                    }
                    catch
                    {
                        conn.Close();
                        conn.Dispose();
                        throw;
                    }
                }
            }
        }

        //執行查詢 返回DataTable  ExecuteDataTable
        public static DataTable ExecuteDataTable(string sql, params SqlParameter[] paras)
        {
            DataTable dt = new DataTable();
            using (SqlDataAdapter adapter = new SqlDataAdapter(sql, constr))
            {
                if (paras != null)
                {

                    adapter.SelectCommand.Parameters.AddRange(paras);
                }
                adapter.Fill(dt);
            }
            return dt;
        }

    }
}
到這里這個封裝的SqlHelper類就好了。然后我會在這里寫一個簡單的小案例。

七、綜合小案例

將第六步做完之后,我們直接使用這個封裝好的SqlHelper

(一)在form1 中拖拉控件,達到以下效果

(二)編寫程序,就是增刪改查,這里我直接放代碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace LoginInfo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //進入窗體之后就加載數據
            LoadDate();
        }

        private void LoadDate()
        {
            String sql = "select * from StudentTable";
           this.dataGridView1.DataSource= SqlHelper.ExecuteDataTable(sql);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string Sname = textBox1.Text.Trim();         //Trim() 移除多余的空格
            string Sage = textBox2.Text.Trim();
            string Ssex = textBox3.Text.Trim();
            string sql = "insert into StudentTable(Sname,Sage,Ssex) values (@Sname,@Sage,@Ssex)";
            //這里是創建參數,更加的安全,防止不法人員注入sql語句,造成錯誤
            SqlParameter[] paras = new SqlParameter[] { 
                    new SqlParameter("@Sname",SqlDbType.NVarChar,50){Value = Sname},
                    new SqlParameter("@Sage",SqlDbType.NVarChar,50){Value = Sage},
                    new SqlParameter("@Ssex",SqlDbType.NVarChar,50){Value = Ssex}
            };
            //因為執行的是插入操作,所以調用ExecuteNonQuery
            int x = SqlHelper.ExecuteNonQuery(sql,paras);
            if (x > 0)
            {
                MessageBox.Show("新增成功");
                //成功的同時,重新加載表格中的數據
                LoadDate();
            }
            else {
                MessageBox.Show("新增失敗");
            
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //行點擊事件,點擊之后,行會吧數據給修改那一欄
            DataGridViewRow current = dataGridView1.CurrentRow;
            textBox6.Text = current.Cells["Sname"].Value.ToString();
            textBox5.Text = current.Cells["Sage"].Value.ToString();
            textBox4.Text = current.Cells["Ssex"].Value.ToString();
            label8.Text = current.Cells["Sid"].Value.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
              string Sname = textBox6.Text;
              string Sage = textBox5.Text;
              string Ssex = textBox4.Text;
              string Sid = label8.Text;
              string sql = "update StudentTable set Sname =@Sname ,Sage = @Sage,Ssex = @Ssex where Sid = @Sid";
              SqlParameter[] paras = new SqlParameter[]{
                    new SqlParameter("@Sname",SqlDbType.NVarChar,50){Value = Sname},
                    new SqlParameter("@Sage",SqlDbType.NVarChar,50){Value = Sage},
                    new SqlParameter("@Ssex",SqlDbType.NVarChar,50){Value = Ssex},
                    new SqlParameter("@Sid",SqlDbType.Int){Value = Sid}

              };
              int x = SqlHelper.ExecuteNonQuery(sql,paras);
              if (x > 0)
              {
                  MessageBox.Show("修改成功");
                  LoadDate();
              }
              else
              {
                  MessageBox.Show("修改失敗");

              }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            string Sid = label8.Text;
            string sql = "delete from StudentTable where Sid = @Sid";
            SqlParameter[] paras = new SqlParameter[]{
                    new SqlParameter("@Sid",SqlDbType.Int){Value = Sid}

              };
            int x = SqlHelper.ExecuteNonQuery(sql, paras);
            if (x > 0)
            {
                MessageBox.Show("刪除成功");
                LoadDate();
            }
            else
            {
                MessageBox.Show("刪除失敗");

            }

        }
       
    }
}
注意:
由於DataGridView還需要設置一些東西:



后續可能還會有補充,由於我是初學,所以有很多東西,不夠詳細,希望諒解

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM