ConnectionString loses password after connection.Open

后端 未结 3 1935
醉梦人生
醉梦人生 2020-12-07 16:26

i\'m using ADO.NET to get some information from the database on a server,
so this is what i do:

string conStr = \"Data Source=myServer\\SQLEXPRESS;Initia         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 17:20

    Look in the connection string, in order to keep the password in the ConnectionString property you must add "Persist Security Info=true;" to the connection string itself.

    The following example will strip the password out:

    string conStr = "Data Source=localhost;Initial Catalog=MyDatabase;User Id=MyUser;Password=MyPassword";
    SqlConnection conn = new SqlConnection(conStr);
    conn.Open();
    conn.Close();
    Console.WriteLine(conn.ConnectionString);
    

    The following example will keep the password in the conn.ConnectionString:

    string conStr = "Persist Security Info=True;Data Source=localhost;Initial Catalog=MyDatabase;User Id=MyUser;Password=MyPassword";
    SqlConnection conn = new SqlConnection(conStr);
    conn.Open();
    conn.Close();
    Console.WriteLine(conn.ConnectionString);
    

    Its a property set inside the connection string itself not in the SqlConnection object, I put it in the beginning of the connection string just so you don't have to scroll to see it, it can go anywhere in the connection string, I usually see it at the end.

    Like others have said, if you need to do this you quite possibly are not using the SqlConnection object exactly as it was intended.

提交回复
热议问题