一、ADO.Net之SqlConnection、SQLCommand知识思维导图
二、ADO.NET提供5个主要的类的对象来实现数据的连接访问和离线访问,这5个类分别是Connection、Command、DataReader、DataAdapter和DataSet。
1.Connection是用来来建立和数据库的连接。
2.Command是用来执行SQL命令和存储过程。
3.DataReader是与DataSet最大的不同是有连接式的,每次对数据库进行存取都会影响到数据库。
4.DataAdapter 是与DataSet配合使用的对象,用于把表填充到DataSet,和更新DataSet等。
三、SqlConnection对象应用
1.使用SqlConnection类可以连接到SQL Server数据库。SqlConnection对象的主要属性和方法如下:
(1)属性:ConnectionString(连接字符串)
(2)方法:Open(打开数据库连接)
Close(关闭数据库连接)
2.连接数据库主要分以下三步:
(1)定义字符串
(2)创建SqlConnection对象:SqlConnection sqlConnection = new SqlConnection();
(3)打开数据库连接:sqlConnection.Open();
四、SqlCommand对象应用
1.SqlCommand属于命令类,SqlCommand 对象用于执行具体的SQL语句,如增加、删除、修改、查找。SqlCommand对象可以用于支持断开连接的数据管理,但我们将只单独使用SqlCommand对象。Sql DataAdapter适配器后面的过程将解释如何使用断开的数据来实现应用程序。
2.使用步骤
(1)创建SqlConnection对象:
SqlConnection connection=new SqlConnection(connectionString);
(2)定义SQL语句:
把所要执行的SQL语句赋给字符串。
(3)创建SqlCommand对象:
SqlCommand command = new SqlCommand();
(4)调用SqlCommand对象的某个方法,执行SQL语句。
注意:在调用SqlCommand对象的某个方法之前,一定要打开数据库连接,否则程序会出错。
举例:
public partial class Form1 : Form
{
//数据库连接字符串
private static string connString = "Data Source=localhost;Initial Catalog=QQ;Integrated Security=true";
//数据库连接对象
public static SqlConnection connection = new SqlConnection(connString);
public Form1()
{
InitializeComponent();
}
//执行SQL语句
private void btnSql_Click(object sender, EventArgs e)
{
try
{
//查询用的 SQL 语句
string selectSql = "select count(*) from Users";
//创建Command对象
SqlCommand command = new SqlCommand();
//指定Command对象所使用的Connection对象
command.Connection = connection;
//指定Command对象用于执行SQL语句
command.CommandType = CommandType.Text;
//指定要执行的SQL语句
command.CommandText = selectSql;
//打开数据库连接
connection.Open();
//执行查询操作,返回单个值
this.txtCount.Text = command.ExecuteScalar().ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
//关闭数据库连接
connection.Close();
}
}
//执行存储过程
private void btnStoreProc_Click(object sender, EventArgs e)
{
try
{
//创建Command对象
SqlCommand command = new SqlCommand();
//指定Command对象所使用的Connection对象
command.Connection = connection;
//指定Command对象用于执行存储过程
command.CommandType = CommandType.StoredProcedure;
//指定要执行的存储过程的名称
command.CommandText = "procSelect1";
//打开数据库连接
connection.Open();
//执行查询操作,返回单个值
this.txtCount.Text = command.ExecuteScalar().ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
//关闭数据库连接
connection.Close();
}
}
}