小弟最近学着做了一段连接数据库登录的代码调试通过,但是登陆后在其他Form里进行数据库操作时,又得重新建立连接: string m ="server='"+comboBox1.Text+"';database=yyxt;uid=sa;pwd=''";
SqlConnection conn=new SqlConnection(m);
conn.Open();
这样很麻烦,况且comboBox1.Text的值还得重新定义成全局变量。能不能把连接数据库的代码定义成一个公用代码,以后用到直接调用即可?
private void button1_Click(object sender, System.EventArgs e)
{
try
{
string m ="server='"+comboBox1.Text+"';database=yyxt;uid=sa;pwd=''";
SqlConnection conn=new SqlConnection(m);
conn.Open();
string sql = "select count(*) from users where UserName='" + textBox1.Text+ "' and UserPwd='" + textBox2.Text+ "'";
SqlCommand cmd=new SqlCommand(sql,conn);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count>0)
{
this.IsLogin = true;
conn.Close();
this.Close(); }
else
{MessageBox.Show("密码或用户名不正确!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);}
}
catch
{
MessageBox.Show("无法与数据库建立连接,请检查网络配置!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
this.button1.Focus();
this.IsLogin = false;
}
}