所以我有一个登录页面,我必须实施验证:'如果用户是" sa"然后它应该使用该用户凭据连接到数据库',这意味着我必须修改我的SqlConnection
对象的凭据:
if(username.Equals("sa", StringComparison.OrdinalIgnoreCase))
{
var securePassword = new System.Security.SecureString();
foreach(char character in password)
{
securePassword.AppendChar(character);
}
securePassword.MakeReadOnly();
var credentials = new SqlCredential(username, securePassword);
sqlConn.Close();
sqlConn.Credential = credentials;
sqlConn.Open();
return true;
}
但即使该属性不是sqlConn.Credential = credentials;
readonly
中获得异常
InvalidOperationException:无法将Credential与UserID,UID,密码或PWD连接字符串关键字一起使用。
还有其他方法可以更改Credentials
属性吗?
提前致谢。
答案 0 :(得分:4)
或者您可以使用SqlConnectionStringBuilder
,
string connectString = "Data source=.;initial catalog=yourDB;
User Id=user; Password=password";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder (connectString);
SqlConnection sqlConn= new SqlConnection(builder.ConnectionString);
然后在你的方法中,
builder.Remove("User Id");
builder.Remove("Password");
// builder.Remove("integrated security"); if you had used
sqlConn.ConnectionString = builder.ConnectionString;
答案 1 :(得分:3)
将引发InvalidOperationException异常:
答案 2 :(得分:1)
如果SqlConnection
有用户名和密码,您似乎可以修改凭据。我使用this教程的示例来使其工作:
if (username.Equals("sa", StringComparison.OrdinalIgnoreCase))
{
using (SqlConnection conn = new SqlConnection(string.Format("Server={0};Initial Catalog={1};", sqlConn.DataSource, sqlConn.Database)))
{
var securePassword = new System.Security.SecureString();
foreach (char character in password)
{
securePassword.AppendChar(character);
}
securePassword.MakeReadOnly();
var credentials = new SqlCredential(username, securePassword);
conn.Credential = credentials;
conn.Open();
return true;
}
}
由于我无法修改Credential
属性,因此我在SqlConnection
username
password
内没有connectionString
和Credential
。这样我可以稍后添加新的ORA-06512: at line 2
06502. 00000 - "PL/SQL: numeric or value error%s"
*Cause: An arithmetic, numeric, string, conversion, or constraint error
occurred. For example, this error occurs if an attempt is made to
assign the value NULL to a variable declared NOT NULL, or if an
attempt is made to assign an integer larger than 99 to a variable
declared NUMBER(2).
*Action: Change the data, how it is manipulated, or how it is declared so
that values do not violate constraints.
No Erro
。希望这可以帮助其他任何面临类似问题的人。