思维导图:
SqlConnection
表示一个到 SQL Server 数据库的打开的连接。
它包含以下属性:
ConnectionString:获取或设置用于打开 SQL Server 数据库的字符串
//获取应用程序配置文件
有以下方法:
Close:关闭与数据库的连接。 此方法是关闭任何已打开连接的首选方法。 (重写 DbConnectionClose。)
open:使用ConnectionString 所指定的属性设置打开数据库连接。 (重写 DbConnectionOpen。)
例如
SqlConnection sqlconnection = new SqlConnection();
sqlconnection.ConnectionString=ConfigurationManager.ConnectionStrings["SQL"].ConnectionString;
sqlconnection.Open();
MessageBox.Show("连接成功");
sqlconnection.Close();
SqlCommand
用于C#编程时对数据库进行操作的类名。SqlCommand对象允许你指定在数据库上执行的操作的类型。比如,你能够对数据库中的行数据执行select,insert,modify以及delete命令。
有以下属性:
1.Connection
获取或设置SqlCommand的实例使用的SqlConnection。
2.CommandText
获取或设置要对数据源执行的Transact-SQL语句或存储过程。
有以下方法:
1.ExecuteNonQuery();
它的返回值类型为int型。多用于执行增加,删除,修改数据。返回受影响的行数。
2.ExecuteScalar();
它的返回值类型多为int类型。它返回的多为执行select查询。得到的返回结果为一个值的情况。
示例:
SqlCommand sqlcommand = new SqlCommand();
sqlcommand.Connection = sqlconnection;
sqlcommand.CommandText = "select COUNT(1) from tb_stuinfo where name=@name and pwd=@pwd "; sqlcommand.Parameters.AddWithValue("@name",txt_number.Text.Trim());
sqlcommand.Parameters.AddWithValue("@pwd", txt_pwd.Text.Trim());
sqlconnection.Open();
int rowCount = (int)sqlcommand.ExecuteScalar()
sqlconnection.Close();