单独写个连库 回头用的地方掉用就行
conn.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
///
/// conn 的摘要说明
///
public class conn
{
public conn()
{ }
public static SqlConnection CreateSqlcon()
{
SqlConnection scon = new SqlConnection("server=localhost;database=XXX;uid=XXX;pwd=XXX;");
return scon;
}
}
登录
protected void Button1_Click1(object sender, EventArgs e)
{
SqlConnection con = conn.CreateDBcon();
con.Open();
string sql = "select * from student where ID=" + this.TextBox1.Text + "and pass=" + this.TextBox2.Text +";
SqlDataAdapter sda = new SqlDataAdapter(sql,con);
DataSet ds = new DataSet();
sda.Fill(ds, "student");
int count = ds.Tables[0].Rows.Count;
if (count != 0)
{
Response.Redirect("学生查看窗口.aspx");
}
else
{
tResponse.Write("用户不存在,或账户、密码错误,请重新登录");
}
}
//连接SQL Server程序代码
string connString = Convert.ToString(ConfigurationManager.ConnectionStrings["sqlconn"]);
SqlConnection conn = new SqlConnection(connString);//创建数据库链接
conn.Open();
string strsql = "select * from stuent where StuName='" + TextBox1.Text + "'and Stupassword='" + TextBox2.Text + "'";
SqlCommand cmd = new SqlCommand(strsql, conn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Session["StuName"] = dr["StuName"];
Session["Stupassword"] = dr["Stupassword"];
if (TextBox1.Text == Session["StuName"].ToString() && TextBox2.Text == Session["Stupassword"].ToString())
{
Response.Redirect("Default2.aspx");
}
}
else
{
Label1.Text = "登陆失败,请检测输入!";
}
web.config中需要配置连接字符串数据
conn.Open();
这里出错,表示连接数据库失败。
解决方法如下:
你的连接字符串:server=localhost;Database=stu_information;uid=sa;pwd=123
localhost 表示本地,请检查你安装的SQL是否有实例名,如果带有实例名,如sqlexpress,则在此处要写成 localhost\sqlexpress 而不是localhost
其次检查数据库名称和用户名密码是否正确。
conn.Open();//这个地方提示有错
具体提示什么错误信息?
没有看到错误,帮不了你
conn.Open();//这个地方提示有错
conn.Close();
这两个去掉