建立数据库连接:
SqlConnection con = new SqlConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ToString();//配置文件中已经配置好连接字符串
con.Open();
对数据库运行的SQL语句。最简单直接的方法是通过ADO和SQL命令对象来实现。
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from Table";
cmd.Connection = con;
DataReaders对象,这个对象仅仅从数据库返回一个只读的,仅向前数据流。而且当前内存中每次仅存在一条记录。
DataReader可以适用于在运行完一条命令仅需要返回一个简单的只读记录集。
完整实例
protected void Button2_Click(object sender, EventArgs e)
{
string name = txtname.Text.ToString();
string pwd = txtpassword.Text.ToString();
SqlConnection con = new SqlConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from Users where UserName = @UserName and PWD = @Pwd";
cmd.Parameters.AddWithValue("@UserName", name);
cmd.Parameters.AddWithValue("@Pwd",pwd);
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
Maticsoft.Common.MessageBox.Show(this, "登录成功!");
}
else {
Maticsoft.Common.MessageBox.Show(this, "登录失败!");
}
con.close();
}
SqlConnection con = new SqlConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ToString();//配置文件中已经配置好连接字符串
con.Open();
对数据库运行的SQL语句。最简单直接的方法是通过ADO和SQL命令对象来实现。
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from Table";
cmd.Connection = con;
DataReaders对象,这个对象仅仅从数据库返回一个只读的,仅向前数据流。而且当前内存中每次仅存在一条记录。
DataReader可以适用于在运行完一条命令仅需要返回一个简单的只读记录集。
完整实例
protected void Button2_Click(object sender, EventArgs e)
{
string name = txtname.Text.ToString();
string pwd = txtpassword.Text.ToString();
SqlConnection con = new SqlConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from Users where UserName = @UserName and PWD = @Pwd";
cmd.Parameters.AddWithValue("@UserName", name);
cmd.Parameters.AddWithValue("@Pwd",pwd);
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
Maticsoft.Common.MessageBox.Show(this, "登录成功!");
}
else {
Maticsoft.Common.MessageBox.Show(this, "登录失败!");
}
con.close();
}