为了账号安全,请及时绑定邮箱和手机立即绑定

为什么会显示实例失败,如何解决?

为什么会显示实例失败,如何解决?

C++
吃鸡游戏 2022-12-15 14:09:03
using System.Data.SqlClient;using System.Configuration;namespace Logon{public partial class Form1 : Form{public Form1(){InitializeComponent();}ManagerForm mf = new ManagerForm();UserForm uf = new UserForm();bool testMyUser(){DBManager db = new DBManager();SqlParameter[] parames=new SqlParameter[3];parames[0] = new SqlParameter("@name",txtName.Text);parames[1] = new SqlParameter("@password",txtPassword.Text);parames[2] = new SqlParameter("@role",cmbRole.Text);DataTable dt = db.SelectMyUser("select * from MyUser where Name=@name and Password=@password and Role=@role",parames);if(dt.Rows.Count>0){return true;}else {return false;}}private void btnLog_Click(object sender, EventArgs e){if(cmbRole.Text=="Manager"){if(testMyUser()){mf.Show();}else {MessageBox.Show("用户名或密码错误!");}}  }class DBManager{public static readonly string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;SqlConnection cn = new SqlConnection(connectionString);public DBManager(){cn.Open();运行时,此处显示cn实例失败}public int RunMyUser(string strSql, SqlParameter[] parames){SqlCommand cm = new SqlCommand();cm.Connection = cn;cm.CommandType = CommandType.Text;cm.CommandText = strSql;cm.Parameters.Clear();if (parames != null){foreach (SqlParameter parame in parames){cm.Parameters.Add(parame);}}int i = cm.ExecuteNonQuery();return i;}public DataTable SelectMyUser(string strSql, SqlParameter[] parames){SqlCommand cm = new SqlCommand();cm.Connection = cn;cm.CommandType = CommandType.Text;cm.CommandText = strSql;cm.Parameters.Clear();if (parames != null){foreach (SqlParameter parame in parames){cm.Parameters.Add(parame);}}SqlDataAdapter da = new SqlDataAdapter();da.SelectCommand = cm;DataSet ds = new DataSet();da.Fill(ds);DataTable dt = ds.Tables[0];return dt;}}}
查看完整描述

2 回答

?
开心每一天1111

TA贡献1836条经验 获得超13个赞

这说明数据库连接失败了
改成
try
{cn.Open();
}
catch(SqlException ex)
{
MessageBox.Show(ex.ToString());
}
看看错误信息,看看是数据库连接字符串的问题,还是其他问题。

查看完整回答
反对 回复 2022-12-18
?
哔哔one

TA贡献1854条经验 获得超8个赞

cn.Open();
把这句话注释掉

查看完整回答
反对 回复 2022-12-18
  • 2 回答
  • 0 关注
  • 74 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信