1.執(zhí)行命令SqlCommand
表示要對SQL Server執(zhí)行的T-SQL語句或存儲過程
SqlCommand對象:Ado.NET中執(zhí)行數(shù)據(jù)庫命令的對象
2.重要屬性:
Connection:SqlCommand對象要是用的SqlConnection
CommandText:獲取或設置T-SQL語句或存儲過程名
CommandType:CommandType.Text--執(zhí)行的是一個Sql語句
CommandType.procedure--執(zhí)行的是一個存儲過程
-------------不帶參的可無
------------帶參的必要有
Parameters:SqlCommand對象的命令參數(shù)幾何 默認為空集合
Transaction:獲取或設置要在其中執(zhí)行的事務
3.創(chuàng)建
1.無參數(shù)
//1.無參數(shù)
SqlCommand cmd = new SqlCommand();//首先通過一個無參構造函數(shù)創(chuàng)建一個Command命令
cmd.Connection = conn;//設置command實例要使用的connection連接對象
cmd.CommandText = sql;
// cmd.CommandType = System.Data.CommandType.Text;因為上面執(zhí)行的是sql語句,所以這句話是沒有必要的,默認不設置
//cmd.CommandType = CommandType.StoredProcedure;//如果執(zhí)行的是存儲過程,必須設置
//cmd.Parameters.Add//Add,AddWithValue單個參數(shù)的添加;AddRang,參數(shù)數(shù)組的添加;
2.一個參數(shù)
//2.一個參數(shù)
SqlCommand cmd1 = new SqlCommand(sql);
cmd1.Connection = conn;//設置與之關聯(lián)的connection
3.兩個參數(shù),sql語句 連接對象 推薦的
//3.兩個參數(shù),sql語句 連接對象 推薦的
SqlCommand cmd2 = new SqlCommand(sql,conn);
4.Connection對象
//4.Connection對象
SqlCommand cmd3 = new conn.CreatCommand();
cmd3.CommandText = sql;
5.事務的
//5.事務的
string delSql="delete from SubsidencePrediction whereId>3";
SqlCommand cmd4 = new SqlCommand(sql,conn ,null );//null為事務,現(xiàn)在沒有
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace SqlCommand執(zhí)行命令
{
class Program
{
static void Main(string[] args)
{
//連接數(shù)不宜過大,防止卡掉
string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
//把using放到try catch中,防止程序終止掉
try
{
using (SqlConnection conn = new SqlConnection(connStr))//通過將連接字符串初始化來,建立連接
{
//打開連接
conn.Open();
//創(chuàng)建命令,執(zhí)行命令的對象,執(zhí)行命令
//命令--表示要對SQL Server執(zhí)行的T-SQL語句或存儲過程(必須在數(shù)據(jù)庫中已經(jīng)創(chuàng)建好),此類不能被繼承
//SqlCommand 表示要對SQL Server執(zhí)行的T-SQL語句或存儲過程
//一個類是對象的抽象,對象是類的實例
//SqlCommand對象:Ado.NET中執(zhí)行數(shù)據(jù)庫命令的對象
//SqlCommand創(chuàng)建
{
string sql = "selext * from SubsidencePrediction";
//1.無參數(shù)
SqlCommand cmd = new SqlCommand();//首先通過一個無參構造函數(shù)創(chuàng)建一個Command命令
cmd.Connection = conn;//設置command實例要使用的connection連接對象
cmd.CommandText = sql;
// cmd.CommandType = System.Data.CommandType.Text;因為上面執(zhí)行的是sql語句,所以這句話是沒有必要的,默認不設置
//cmd.CommandType = CommandType.StoredProcedure;//如果執(zhí)行的是存儲過程,必須設置
//cmd.Parameters.Add//Add,AddWithValue單個參數(shù)的添加;AddRang,參數(shù)數(shù)組的添加;
//2.一個參數(shù)
SqlCommand cmd1 = new SqlCommand(sql);
cmd1.Connection = conn;//設置與之關聯(lián)的connection
//3.兩個參數(shù),sql語句 連接對象 推薦的
SqlCommand cmd2 = new SqlCommand(sql,conn);
//4.Connection對象
SqlCommand cmd3 = new conn.CreatCommand();
cmd3.CommandText = sql;
//5.事務的
string delSql="delete from SubsidencePrediction whereId>3";
SqlCommand cmd4 = new SqlCommand(sql,conn ,null );//null為事務,現(xiàn)在沒有
}
// conn.Close();
}
}
catch (Exception ex)
{
throw;
}
}
}
}