ADO.Net中SqlConnection、 Sqlcommand学习笔记
SqlConnection对象
SqlConnection类可以连接到SQL Server数据库。SqlConnection对象属性有ConnectionString,连接字符串。方法有open()、close()表示数据库的打开和关闭等。
SqlConnection对象的使用步骤
1、定义连接字符串。2、创建SqlConnection对象。3、打开数据库连接。
SqlConnection类用于建立到SQL Server数据库的开放连接。这是一个封闭的类,所以不能被继承。连接到Microsoft SQL Server数据库时,SqlConnection类与SqlDataAdapter和SqlCommand类一起使用来提高性能。
创建SqlConnection对象可以有:
SqlConnection connection = new SqlConnection("data source=.; database=SampleDB; integrated security=SSPI");
SqlConnection connection = new SqlConnection(); connection.ConnectionString = "data source=.; database=SampleDB; integrated security=SSPI";
SqlCommand对象
SqlCommand对象用于执行具体的SQL语句,如增加、删除、修改、查找。方法有:
1、ExecuteScalar()---执行查询,并返回查询结果中的第一行第一列的值,类型是object。
2、ExecuteNonQuery()---执行SQL语句并返回受影响的行数。
3、ExecuteReader()---执行查询命令,返回SqlDataReader对象。
SqlCommand对象的使用步骤
1、创建SqlConnection对象。2、定义SQL语句。3、创建SqlCommand对象。4、调用SqlCommand对象的某个方法,执行SQL语句。
实例
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString =
"Server=(local);Database=EduBaseDemo;Integrated Security=sspi";
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText =
"SELECT COUNT(1) FROM tb_User"
+ " WHERE No='" + this.txb_UserNo.Text.Trim() + "'"
+ " AND Password=HASHBYTES('MD5','" + this.txb_Password.Text.Trim() + "');";
sqlConnection.Open();
int rowCount = (int)sqlCommand.ExecuteScalar();
sqlConnection.Close();
if (rowCount == 1)
{
MessageBox.Show("登录成功。");
}
else
{
MessageBox.Show("用户号/密码有误,请重新输入!");
this.txb_Password.Focus();
this.txb_Password.SelectAll();
}
}
}
思维导图