我一直在尝试通过App.config中的连接字符串连接到我的MS Sql数据库,但由于某种原因它无法登录,我似乎无法弄明白。
这是我的Connection方法:
public void Con()
{
string userName = userNameBox.Text;
string passWord = passWordBox.Text;
bool loginFail;
SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["lagerConn"].ConnectionString);
//Search Connstring for User ID= & Password= and replace with username and password from Textboxes
if (_Connstring.Contains("User ID="))
{
_Connstring = _Connstring.Replace("User ID=;", "User ID=" + userName + ";");
}
if (_Connstring.Contains("Password="))
{
_Connstring = _Connstring.Replace("Password=", "Password='" + passWord + "'");
}
try
{
Conn.Open();
Conn.Close();
loginFail = false;
}catch
{
MessageBox.Show("Login Failed");
loginFail = true;
}
if(loginFail == false) //If login is successful it will change to the next form and hide the Connect form
{
mainMenu secondForm = new mainMenu();
secondForm.Show();
this.Hide();
}
}`
这是我的App.config
<add name="lagerConn" connectionString="Data Source=LagerServer;Initial Catalog=LagerDB;Persist Security Info=True;User ID=;Password="
providerName="System.Data.SqlClient" />
</connectionStrings>
答案 0 :(得分:2)
根本没有必要在连接字符串中放置一个空的用户ID和密码字段。完全抛弃它们,摆脱那无意义的Persist Security Info
。使用连接字符串构建器,例如
SqlConnection builder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["lagerConn"].ConnectionString);
builder.UserID = userID;
builder.Password = password;
SqlConnection connection = new SqlConnection(builder.ConnectionString);
之后,不要只提供一般性错误消息并忽略系统提供给您的信息。看一下例外,它会告诉你出了什么问题。
答案 1 :(得分:0)
尝试:
string userName = userNameBox.Text;
string passWord = passWordBox.Text;
string connStr = ConfigurationManager.ConnectionStrings["lagerConn"].ConnectionString;
connStr = connStr.Replace("User ID=;", "User ID=" + userName + ";");
connStr = connStr.Replace("Password=", "Password='" + passWord + "'");
bool loginFail = false;
try{
using (SqlConnection Conn = new SqlConnection(connStr){
loginFail true;
}
}
catch (SqlConnection sqlEx){
//already false
}
是的,谨防sql注入攻击!
答案 2 :(得分:0)
首先,你不应该在TextBox中编写UserID和Password,在连接字符串中将它们写为静态。例外告诉你一切 - &gt;用户''登录失败。您没有在文本框中写入正确的用户名或密码。