怎样讲数据操作写成一个类,要怎么调用,要如何在web.config里配置数据库连接?本人是菜鸟,以我附加的代码为例子,尽量详细点!谢谢!!!
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class reg : System.Web.UI.Page
{
static string connection = "Data Source=PC-201109290903;Initial Catalog=#Home#Malihome@2011;Integrated Security=True";
private SqlConnection sqlConnection1 = new SqlConnection(connection);
private SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter();
private DataSet dataSet11 = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
//諾帳號文本框內為空
if (username.Text == "")
{
LabelMessage.Text = "<script language='Jscript'>" + "alert('您必須輸入帳號!');</script>";
}
else
{
string number = this.username.Text;
SqlCommand myCommand = this.sqlConnection1.CreateCommand();
myCommand.CommandText = "select * from HTX_Member where username='" + number + "'";
this.sqlDataAdapter1.SelectCommand = myCommand;
dataSet11.Clear();
int n = this.sqlDataAdapter1.Fill(dataSet11, "HTX_Member");
if (n != 0)
LabelMessage.Text = "<script language='Jscript'>" + "alert('您輸入的帳戶號已經被占用,請重新輸入!');</script>";
else
{
LabelMessage.Text = "";
if (userpwd.Text != userpwd1.Text )
LabelMessage.Text = "<script language='Jscript'>" + "alert('密碼與重複密碼不一致,請重新輸入密碼和重複密碼!');</script>";
else
{
LabelMessage.Text = "";
if (useremail.Text != useremail1.Text)
LabelMessage.Text = "<script language='Jscript'>" + "alert('輸入的Email与電郵不一致,請重新輸入!');</script>";
else
{
LabelMessage.Text = "";
}
try
{
myCommand.CommandText = "insert into HTX_Member(username,useremail,userpwd)" + "values(@username,@useremail,@userpwd)";
myCommand.Parameters.Add("@username", SqlDbType.NVarChar, 50, "username");
myCommand.Parameters.Add("@useremail", SqlDbType.NVarChar, 50, "useremail");
myCommand.Parameters.Add("@userpwd", SqlDbType.NVarChar, 50, "userpwd");
myCommand.Parameters["@username"].Value = username.Text;
myCommand.Parameters["@useremail"].Value = useremail.Text;
myCommand.Parameters["@userpwd"].Value = userpwd.Text;
sqlConnection1.Open();
myCommand.ExecuteNonQuery();
sqlConnection1.Close();
LabelMessage.Text = "您已經成功註冊!";
}
catch (Exception Exc)
{
LabelMessage.Text = Exc.Message;
sqlConnection1.Close();
}
}
}
}
}
}
你这样写不是很好,把Script都写到数据操作层上,现在网上都有比较好的数据库操作类,你可以百度搜索下来看,理解并且试着自己写一边,至于配置web.config,网上教程很多,如果你理解web.config里面节点的含义,那就不是问题了。
建议你网上找下 Microsoft 的PetShop 4 把里边的学了就差不多了。
给个链接吧!
static string connection =System.Configuration.ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
能不能给写参考资料啊!
建议你找微软官方的数据库操作类,大部分流行的数据库的操作类,微软都有提供。都是经过测试经过考验的。
给个链接吧 !!!
你给个百度一下 三层架构 你这样写以后维护很麻烦!
搞个DBHelper类,把所有操作数据的方法都封装进去然后业务层直接调用里面的方法就好了,分层可以降低代码的耦合度便于以后维护,另外登录时候一些非空的验证可以使用验证控件或者写前台JS脚本。