请帮帮我...过去两天我面临这个问题
我的连接类
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);
}
}
我不是要求你为我调试代码...请指出错误是什么..我是初学者所以请...
答案 0 :(得分:5)
这里的问题是你试图在构造函数中实例化Connection类的字段,而不是创建局部变量。因此,就范围而言,您隐藏了conn
和cmd
变量。
试试这个:
public Connection()
{
conn = new SqlConnection(@"server=ADMIN-PC;database=sample;Integrated security=true");
cmd = null;
}
答案 1 :(得分:2)
试试这段代码
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();
}
}
答案 2 :(得分:0)
虽然已经选择了答案(这完全解决了这里的问题),但我仍然想发布使用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);
}
}