您的位置:首页 > 其它

【牛腩新闻发布系统】静态方法和非静态方法的调用

2016-10-09 22:35 351 查看

非静态方法

       非静态方法在调用时需要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());  //非静态方法的实例化

}
}
}

参考链接

       静态方法与非静态方法的区别

       JAVA的静态变量、静态方法、静态类

感谢您的宝贵时间,祝生活愉快,谢谢~
                                                                                                                    ——joker
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: