对象引用未设置为对象的实例.(C#web应用程序)
本文关键字:C#web 应用程序 实例 设置 对象 对象引用 | 更新日期: 2023-09-27 18:19:26
请帮帮我……从过去两天起,我面临这个问题
我的连接类
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);
}
}