以下是我的主要例子:
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
sqlconnect sql = new sqlconnect();
public string pass;
public string user;
public void button1_Click(object sender, EventArgs e)
{
//Username and password textboxes send to public strings
user = textBox1.Text;
pass = textBox2.Text;
try
{
//try connecting to SQL database using SQL class
sql.GetSqlConnection();
sql.myConnection.Open();
this.Hide();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
这是SQL连接类:
namespace NHS_Workshop_System
{
public class sqlconnect
{
public SqlConnection myConnection { get; set; }
Settings1 set = new Settings1();
Login var = new Login();
public SqlConnection GetSqlConnection()
{
if (myConnection == null)
myConnection = new SqlConnection("user id="+(var.user)+"; password="+(var.pass)+";server="+(set.SelectServer)+";Trusted_Connection="+(set.SelectContype)+";database="+(set.SelectDataBase)+"; connection timeout="+(set.Condrop)+"");
return myConnection;
}
}
}
因此,当我尝试登录时,它可能是第一次工作,但如果另一个表单尝试运行该方法,则缺少用户名和密码。我不确定如何使变量全局化,以便每次运行该方法时它都会调用这些详细信息。所以第二次在另一个表单上使用sqlconnection时,ex消息表明用户名和密码不存在。这是否是一个范围问题,如果有人能说明我可能会如何解决这个问题,这可能是一种获取SQL服务器访问权限的新方法?谢谢你撕掉我的头发
答案 0 :(得分:1)
以下是您现在的问题的答案。但我强烈建议你考虑一下你正在做什么,因为你的课程逻辑看起来不是很好。我看到你试图实现Singleton是好的,但如果你愿意,你仍然可以创建更多的sqlconnect实例。
在您的Login类中,传递此Login实例,以便sqlconnector知道用户并传递此处声明的内容。
public partial class Login : Form
{
// Old style - sqlconnect sql = new sqlconnect();
sqlconnect sql;
public string pass; // These arent declared and wont be of use for your sql connect class
public string user;
public Login( String pass, String user )
{
this.pass = pass;
this.user = user;
// Now that we have a login with declared variables, pass it to the sqlconnect object
this.sql = new sqlconnect(this);
InitializeComponent();
}
现在在您的sqlconnect类中,在您的Login变量为空之前。现在你已经在你的构造函数中收到了它的变量集的实例
public class sqlconnect
{
public SqlConnection myConnection { get; set; }
Settings1 set = new Settings1();
// Here you maked a new one, use the existing instead from which this class is called.
// changed variable named from var to login..
Login login;
// *NEW* Constructor where you pass your login object
public sqlconnect(Login login)
{
this.login = login;
}
public SqlConnection GetSqlConnection()
{
if (myConnection == null)
myConnection = new SqlConnection("user id="+(login.user)+"; password="+(login.pass)+";server="+(set.SelectServer)+";Trusted_Connection="+(set.SelectContype)+";database="+(set.SelectDataBase)+"; connection timeout="+(set.Condrop)+"");
return myConnection;
}
}