[英]Object reference not set to an instance of an object.(C# web application)
请帮助我...从最近两天开始我就遇到这个问题
我的连接课程
public class Connection
{
SqlConnection conn;
SqlCommand cmd;
public void connclose()
{
conn.Close();
}
public Connection()
{
SqlConnection conn = new SqlConnection(@"server=ADMIN-PC;database=sample;Integrated security=true");
SqlCommand cmd = null;
}
public void nonquery(string qry)
{
conn.Open();
cmd = new SqlCommand(qry, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
我的课
public class Master
{
Connection conn = new Connection();
public void insert(string name, string place, string company, string post)
{
string qry = "insert into company values('" + name + "','" + place + "','" + company + "'.'" + post + "')";
conn.nonquery(qry);
}
}
我不是要您为我调试代码...请指出错误的原因..我是初学者,所以请..
这里的问题是您试图在构造函数中实例化Connection类的字段,而不是创建局部变量。 因此,就范围而言,您隐藏了conn
和cmd
变量。
尝试这个:
public Connection()
{
conn = new SqlConnection(@"server=ADMIN-PC;database=sample;Integrated security=true");
cmd = null;
}
试试这个代码
public class Connection
{
SqlConnection conn;
SqlCommand cmd;
public void connclose()
{
conn.Close();
}
public Connection()
{
// initializing global variables
conn = new SqlConnection(@"server=ADMIN-PC;database=sample;Integrated security=true");
cmd = null;
}
public void nonquery(string qry)
{
conn.Open();
cmd = new SqlCommand(qry, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
尽管已经选择了答案(这在这里完全解决了问题),但是我仍然想发布使用SqlCommand参数的答案。
public class Connection
{
SqlConnection conn;
SqlCommand cmd;
public void connclose()
{
conn.Close();
}
public Connection()
{
conn = new SqlConnection(@"server=ADMIN-PC;database=sample;Integrated security=true");
cmd = null;
}
public void nonquery(string qry, string[] arrParams, string[] arrParamsVals)
{
try
{
conn.Open();
cmd = new SqlCommand(qry, conn);
for(int i=0; i < arrParams.Length; i++)
cmd.Paratmeters.AddWithValue(arrParams[i], arrParamsVals[i]);
cmd.ExecuteNonQuery();
}
catch{}
finally { conn.Close(); }
}
}
大师班
public class Master
{
Connection conn = new Connection();
public void insert(string name, string place, string company, string post)
{
string qry = "Insert into company values(@name, @place, @company, @post)";
string[] arrParams= {"@name", "@place", "@company", "@post"};
string[] arrParamsVals= {name, place, company, post};
conn.nonquery(qry, arrParams, arrParamsVals);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.