在下新手,在数据库编程时做书上的例子,通过c#程序登录界面,登录到一个数据库,我使用了本地服务器。在SQL server management studio中,使用账号sa以sqlserver身份验证方式可以登录服务器名为HY-20141014UKZE\SQLEXPRESS的数据库引擎,并且创建了一个名为Fiancing的数据库, 参考书上的例子如下,怎么样可以在这个c#程序中登录Fiancing数据库?
private void btnLogin_Click(object sender, EventArgs e)
{
string userName = txtName.Text.Trim();//Trim()用于去除文本框中的前后空格
string password = txtPwd.Text.Trim();
string connString = "Data Source=.;Initial Catalog=Financing;User ID=sa;Pwd=123456";
SqlConnection conn = new SqlConnection(connString);//创建Connection对象
//获取用户名和密码匹配的行的数量的SQL语句
string sql = String.Format("select count(*)from User where UserName='{0}'and Password='{1}'",userName,password);
try
{
conn.Open();//打开数据库连接
SqlCommand comm = new SqlCommand(sql, conn);//封装sql命令
int num = (int)comm.ExecuteScalar();//执行sql命令
if (num ==1)
{
//如果有匹配的行,则表明用户名和密码正确
MessageBox.Show("欢迎进入个人理财系统!", "登陆成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
MainFrm mainForm=new MainFrm();
mainForm.Show();
this.Visible=false;
}
else
{
txtPwd.Text="";//清除文本框中的内容
MessageBox.Show("您输入的用户名或密码有误!", "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "操作数据库出错!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
conn.Close();
}
}