非静态方法
非静态方法在调用时需要new一个实例。
namespace DAL
{
public class SQLHelper
{
public int test() //非静态方法
{
//数据库连接字符串
string connStr = @"Server=JokerLiu\SQLEXPRESS;Database=newssystem;User ID=sa;Password=1";
//创建数据库连接对象,传入数据库连接字符串
SqlConnection conn = new SqlConnection(connStr);
//打开数据库连接
conn.Open();
//SQL语句
string sql = "insert into T_category(name) values('测试')";
//创建command执行对象
SqlCommand cmd = new SqlCommand(sql, conn);
//接收返回值
int result = cmd.ExecuteNonQuery();
//关闭数据库连接
conn.Close();
return result;
}
}
}
namespace Web
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write (new SQLHelper ().test ()); //非静态方法的实例化
}
}
}
静态方法
静态方法直接调用,但是需要初始化。
namespace DAL
{
public class SQLHelper
{
public static int test() //静态方法
{
//数据库连接字符串
string connStr = @"Server=JokerLiu\SQLEXPRESS;Database=newssystem;User ID=sa;Password=1";
//创建数据库连接对象,传入数据库连接字符串
SqlConnection conn = new SqlConnection(connStr);
//打开数据库连接
conn.Open();
//SQL语句
string sql = "insert into T_category(name) values('测试')";
//创建command执行对象
SqlCommand cmd = new SqlCommand(sql, conn);
//接收返回值
int result = cmd.ExecuteNonQuery();
//关闭数据库连接
conn.Close();
return result;
}
}
}
namespace Web
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write (DAL.SQLHelper.test()); //非静态方法的实例化
}
}
}
参考链接
感谢您的宝贵时间,祝生活愉快,谢谢~
——joker