标签:知识 base dem 代码 语句 创建 密码 类型 command
ADO.Net之SqlConnection、 Sqlcommand的应用。
知识点:
1.为了能够使用SQLConnection类,我们首先需要引用命名空间System.Data.SqlClient(using System.Data.SqlClient);接着创建SQLConnection类型的实例对象
mSqlConnection,为其属性ConnectionString赋值连接字符串;然后调用Open()方法,这就完成了数据库的连接操作;最后在完成访问数据操作之后,调用Close()方法,关闭连接。
2.基于连接的对象。它们是数据提供程序对象,如Connection、Command。它们连接到数据库,执行SQL语句,遍历只读结果集或者填充DataSet。基于连接的对象是针对具体数据源类型的,并且可以在提供程序制定的命令空间中(例如SQL Server提供程序的System.Data.SqlClient)找到
一、SqlConnection的应用
连接数据库,实现简单的登录功能,代码如下:
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.txt_user.Text.Trim() + "‘"
+ " AND
Password=HASHBYTES(‘MD5‘,‘" + this.txt_pass.Text.Trim() + "‘);";
sqlConnection.Open();
int rowCount =
(int)sqlCommand.ExecuteScalar();
sqlConnection.Close();
if (rowCount ==
1)
{
MessageBox.Show("您好,登录成功。");
}
else
{
MessageBox.Show("用户号或密码错误,请重新输入");
this.txt_pass.Focus();
this.txt_pass.SelectAll();
}
二、SQLCommand的应用
连接数据库,实现简单的查询功能
string connString = "Data Source=(local);Initial Catalog=EduBaseDemo;User
Id=userId;Password=password";
using
(SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
string sql = @"select * from table";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
ADO.Net之SqlConnection、 Sqlcommand的应用。
标签:知识 base dem 代码 语句 创建 密码 类型 command
原文地址:https://www.cnblogs.com/YunQiDick/p/9691998.html