连接SQL方法
一。在SQLHelper类中输入
public class SQLHelper //助手类
{
//测试方法
public int test()
{
string connStr = @"server=SIKU;database=newssystem;uid=sa;pwd=123456";//连接字符串
SqlConnection conn = new SqlConnection(connStr );//连接数据库
conn.Open();//打开数据库
string sql = "insert into category(name) values('娱乐新闻')";//SQL语句
SqlCommand cmd = new SqlCommand(sql ,conn );//执行SQL语句
int res = cmd.ExecuteNonQuery();//返回执行SQL后影响的行数
conn.Close();//关闭连接
return res;
}
}
注:常见错误:
1。连接字符串错误,如:IP错误,密码不对等
2。没有打开连接
二。在Default.aspx.cs中输入测试代码:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(new SQLHelper ().test() );
}
注:易错处:
1。SQLHelper类没有实例化(new一下)
2。没有添加引用
3。没有USING DAL