在解决方案里面新添加类库,在类库里面创建一个静态实例,代码写好后,在.cs在调用这个这个类,通过调用这个类来实现数据的操作.具体代码如下:
1:数据库连接类 (SQLHelper),
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace DAL
{
public class SQLHelper
{
public static int SqlConnection()
{
string connStr = @"server=op\SQLEXPRESS;database=newssystem;uid=sa;pwd=123456";
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
string sql = "select * from news";
SqlCommand cmd = new SqlCommand(sql, conn);
int res = cmd.ExecuteNonQuery();
conn.Close();
return res;
}
}
}
2:.CS页面调用这个类.(先引用)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using DAL;
public partial class sql : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(SQLHelper.SqlConnection());
}
}
呵呵,代码很幼稚,但是我在开始了.加油.