简体   繁体   English

计算有多少用户添加到数据库

[英]Count how many users are added to database

I have some code which collect all users from Active Directory and INSERTs them into my database.我有一些代码可以从Active Directory收集所有用户并将它们插入到我的数据库中。 After I have inserted all users which don't already exist in my database I want to count how many new users I added to the database.插入数据库中尚不存在的所有用户后,我想计算我添加到数据库中的新用户数量。

So far want I create is this which is function to Execute store procedure到目前为止,我要创建的是 function 来执行存储过程

 public void ExcStrPrc(string Username, string DisplayName, bool isEnable, bool PassNevExp)
        {
            SqlConnection conn = new SqlConnection(@"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True");
            SqlCommand cmd = new SqlCommand("ADProcTemp", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Username", Username.ToString().Trim());
            cmd.Parameters.AddWithValue("@DisplayName", DisplayName.ToString().Trim());
            cmd.Parameters.AddWithValue("@isEnabled", Convert.ToInt32(isEnable));
            cmd.Parameters.AddWithValue("@PassNevExp", Convert.ToInt32(PassNevExp));
            conn.Open();
            int k = cmd.ExecuteNonQuery();
            if (k != 0)
            {
                Console.WriteLine("Record Inserted Succesfully into the Database");

            }           
            conn.Close();
        }

And here is my main program这是我的主要程序

        public static List<Korisnik> VratiKorisnike()
        {
            List<Korisnik> lstADUsers = new List<Korisnik>();
            string sDomainName = "saostest";
            string DomainPath = "LDAP://" + sDomainName;
            string fileLoc = @"C:\output.txt";

            DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
            DirectorySearcher search = new DirectorySearcher(searchRoot);

            search.Filter = "(&(objectClass=user)(objectCategory=person))";
            search.PropertiesToLoad.Add("samaccountname"); // Username
            search.PropertiesToLoad.Add("displayname"); // display name
            search.PropertiesToLoad.Add("userAccountControl");  // isEnabled
            search.PropertiesToLoad.Add("pwdLastSet"); //passwordExpires


            DataTable resultsTable = new DataTable();
            resultsTable.Columns.Add("samaccountname");
            resultsTable.Columns.Add("displayname");
            resultsTable.Columns.Add("Neaktivan");
            resultsTable.Columns.Add("dontexpirepassword");

            SearchResult result;
            SearchResultCollection resultCol = search.FindAll();


            if (resultCol != null)
            {
                for (int counter = 0; counter < resultCol.Count; counter++)
                {
                    string UserNameEmailString = string.Empty;

                    result = resultCol[counter];

                    if (result.Properties.Contains("samaccountname")
                        && result.Properties.Contains("displayname"))
                    {
                        int userAccountControl = Convert.ToInt32(result.Properties["userAccountControl"][0]);
                        string samAccountName = Convert.ToString(result.Properties["samAccountName"][0]);

                        int isEnable;
                        int Dont_Expire_Password;


                        if ((userAccountControl & 2) > 0)
                        {
                            isEnable = 0;
                        }
                        else
                        {
                            isEnable = 1;
                        }



                        if ((userAccountControl & 65536) > 0)
                        {
                            Dont_Expire_Password = 1;
                        }
                        else
                        {
                            Dont_Expire_Password = 0;
                        }


                        Korisnik korisnik = new Korisnik();
                        korisnik.Username = (result.Properties["samaccountname"][0]).ToString();
                        korisnik.DisplayName = result.Properties["displayname"][0].ToString();
                        korisnik.isEnabled = Convert.ToBoolean(result.Properties["userAccountControl"][0]);


                        DataRow dr = resultsTable.NewRow();
                        dr["samaccountname"] = korisnik.Username.ToString();
                        dr["displayname"] = korisnik.DisplayName.ToString();
                        dr["neaktivan"] = Math.Abs(isEnable);
                        dr["dontexpirepassword"] = Dont_Expire_Password;    

                        resultsTable.Rows.Add(dr);

                        // Poziva se store procedura
                        Program p = new Program();
                        p.ExcStrPrc(korisnik.Username.ToString().Trim(), korisnik.DisplayName.ToString().Trim(), Convert.ToBoolean(isEnable), Convert.ToBoolean(Dont_Expire_Password));

                        //Ukupan broj dodanih novih usera 
                        string connectionString = @"Data Source = (LocalDb)\MSSQLLocalDB; Initial Catalog = DesignSaoOsig1; Integrated Security = True";
                        System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
                        sqlConnection.Open();
                        System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand("SELECT COUNT(*) FROM [dbo].[tblZaposleni_AD]");
                        sqlCommand.Connection = sqlConnection;

                        int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
                        Console.WriteLine("Ukupan broj dodanih novi usera:", sqlCommand);

                        lstADUsers.Add(korisnik);    
                    }
                }
                var json = JsonConvert.SerializeObject(resultCol, Formatting.Indented);
                var res = json;

                Console.WriteLine("Ispis uspjesno obavljen");
                Console.ReadLine();
                File.WriteAllText(fileLoc, json);    
            }
            return lstADUsers;
        }
    }
}

Right here I add these logic在这里我添加这些逻辑

string connectionString = @"Data Source = (LocalDb)\MSSQLLocalDB; Initial Catalog = DesignSaoOsig1; Integrated Security = True";
                    System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
                    sqlConnection.Open();
                    System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand("SELECT COUNT(*) FROM [dbo].[tblZaposleni_AD]");
                    sqlCommand.Connection = sqlConnection;

                    int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
                    Console.WriteLine("Ukupan broj dodanih novi usera:", sqlCommand);

But here is problem which I didn't get any result (number)?但这是我没有得到任何结果(数字)的问题? Anyone how can help me to solve this problem?任何人都可以如何帮助我解决这个问题?

Stored Procedure存储过程

CREATE PROCEDURE ADProcTemp
@Username varchar(250),
@DisplayName varchar(70),
@isEnabled tinyint,
@PassNevExp tinyint
AS
set nocount on
BEGIN
    IF NOT EXISTS (SELECT TOP 1 PrezimeIme FROM [dbo].[tblZaposleni_AD] with (NOLOCK) WHERE NetworkLogin = @Username)                   
BEGIN
    IF(@isEnabled = 1)
   INSERT INTO [dbo].[tblZaposleni_AD](NetworkLogin,PrezimeIme,Status,PassNevExp)
   VALUES (@Username, @DisplayName, @isEnabled,@PassNevExp)
END
ELSE    
BEGIN
  UPDATE [dbo].[tblZaposleni_AD]  
  SET Status = @isEnabled
  WHERE NetworkLogin = @Username AND Status <> @isEnabled

END
END

First in your stored procedure you need to remove SET NOCOUNT ON in order to allow the sp to return the number of row affected.首先,在您的存储过程中,您需要删除SET NOCOUNT ON以允许 sp 返回受影响的行数。

Then in your c# code instead of然后在您的 c# 代码中,而不是

int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());

You need to call this你需要调用这个

int RecordCount = Convert.ToInt32(sqlCommand.ExecuteNonQuery());

From the MSDN doc:从 MSDN 文档:

ExecuteScalar

Returns退货

Object Object

The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty.结果集中第一行的第一列,如果结果集为空,则为 null 引用(Visual Basic 中为 Nothing)。 Returns a maximum of 2033 characters.返回最多 2033 个字符。

ExecuteNonQuery

Returns退货

Int32整数32

The number of rows affected.受影响的行数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM