March 2008
Intermediate to advanced
982 pages
22h 43m
English
You need to programmatically change the existing password for the user specified in a connection string to SQL Server 2005 or later.
Use the ChangePassword() method of the SqlConnection class.
The solution uses the ChangePassword() method of the SqlConnection class to change the password for the user named sa (system administrator) and confirms the change by logging in with the new password.
The C# code shown in Program.cs in the project ChangeSqlServerUserPassword is shown in Example 11-20.
Example 11-20. File: Program.cs for ChangeSqlServerUserPassword solution
using System; using System.Data; using System.Data.SqlClient; namespace ChangeSqlServerUserPassword { class Program { static void Main(string[] args) { string password1 = "password"; string password2 = "new-password"; string sqlConnectString1 = "Data Source=(local);" + "uid=sa;pwd=" + password1 + ";Initial Catalog=AdventureWorks;"; // Using password1 to connect, change the password to password2 SqlConnection.ChangePassword(sqlConnectString1, password2); Console.WriteLine("Password changed to '{0}'.", password2); // Open a connection using the new password (password2) string sqlConnectString2 = "Data Source=(local);" + "uid=sa;pwd=" + password2 + ";Initial Catalog=AdventureWorks"; using (SqlConnection conn = new SqlConnection(sqlConnectString2)) { conn.Open( ); Console.WriteLine("\nConnected with connect string:\n {0}", sqlConnectString2); } Console.WriteLine("\nDisconnected."); ...Read now
Unlock full access