0

I have problem regarding inserting the loop process. So when the connection string determine that the server is down, the inserting process stop looping. My question, is there way to determine whether this connection string is down or not? I have research they answer is to make if condition sqlconn.State == ConnectionState.Open I will show you guys the sample error that I encounter.

Error

        string connetionString = null;
        MySqlConnection cnn;
        connetionString = "server=localhost;database=sample_db_xx;uid=root;pwd=;";
        cnn = new MySqlConnection(connetionString);

        try
        {
            var arpp_pro = new List<string>();

            cnn.Open();

            MySqlCommand command = new MySqlCommand("SELECT store_id,CONCAT(boh,'\\\\sqlexpress') as boh FROM db_cua.stores WHERE " +
                "is_active = 1 AND boh != '' ", cnn);

            using (MySqlDataReader reader = command.ExecuteReader())
            {

                while (reader.Read())
                {
                    Console.WriteLine(reader[0].ToString());
                    arpp_pro.Add(reader[1].ToString());

                }

            }
            cnn.Close();


            foreach (var arpp_pro_data in arpp_pro)
            {

                string connetionString_SQL = @"Server=" + arpp_pro_data + " \sqlexpress;Database=Site5;User ID=sa;Password=dospos";

                    //@"Server=" + arpp_pro_data + ";Database=Site5;User ID=sa;Password=dospos";

                var date_minus_one_day = DateTime.Today.AddDays(-1);
                var formatted_date_minus_one_day = date_minus_one_day.ToString("yyyy-MM-dd");
                var year = DateTime.Now.ToString("yyyy");
                var month = DateTime.Now.ToString("MM");
                var date = DateTime.Today.AddDays(-1);
                var date_formatted = date.ToString("dd");

                string get_sos_orders_details = @"SELECT 
                Convert(nvarchar(50),dbo.SOS_ORDERS.OrderId)+ '-'+ Convert(nvarchar(50),dbo.SOS_ORDERS.TransTime) + Convert(nvarchar(50),dbo.Sales.TransactionId)+ Convert(nvarchar(50),dbo.Sales.TotalDeptName) as result,
                dbo.Sales.StoreId,
                Convert(nvarchar(50),dbo.SOS_ORDERS.TransTime) as TransTime,
                dbo.Transactions.OperatorName as Cashier,
                dbo.Sales.TotalDeptName as Transaction_Type,
                dbo.Sales.TransactionId,
                (dbo.SOS_ORDERS.DTOT + dbo.SOS_ORDERS.ASSM) as Cashier_Time,
                (dbo.SOS_ORDERS.KIT) as Preparation_Time,
                (dbo.SOS_ORDERS.KIT + dbo.SOS_ORDERS.DTOT + dbo.SOS_ORDERS.ASSM) as Total_Time
                FROM dbo.SOS_ORDERS INNER JOIN
                dbo.Sales ON dbo.SOS_ORDERS.OrderId = dbo.Sales.StoredOrderIndex INNER JOIN
                dbo.Transactions ON dbo.Sales.Sequence = dbo.Transactions.Sequence


                where dbo.Sales.businessdate= @date_minus_one_day
                OR(DATEPART(yy, dbo.SOS_ORDERS.TransTime) = @year
                AND DATEPART(mm, dbo.SOS_ORDERS.TransTime) = @month
                AND DATEPART(dd, dbo.SOS_ORDERS.TransTime) = @date_today )



                AND(dbo.Sales.TotalDeptName in ('01 SALLE MANGER', '02 EMPORTER')
                or dbo.Sales.TotalDeptName in ('01 DINE IN', '02 TAKE OUT'))
                GROUP BY dbo.SOS_ORDERS.OrderId,  dbo.Sales.StoreId, dbo.SOS_ORDERS.TransTime, dbo.SOS_ORDERS.DTOT, dbo.SOS_ORDERS.LINE, dbo.SOS_ORDERS.WIND, dbo.SOS_ORDERS.SERV, dbo.SOS_ORDERS.HOLD,
                dbo.SOS_ORDERS.TOTL, dbo.SOS_ORDERS.ASSM, dbo.SOS_ORDERS.CASH, dbo.SOS_ORDERS.FTOT, dbo.SOS_ORDERS.PAY, dbo.SOS_ORDERS.KIT, dbo.Sales.TransactionId,
                dbo.Transactions.OperatorName, dbo.Sales.TotalDeptName order by dbo.SOS_ORDERS.TransTime DESC";

                using (SqlConnection sqlconn = new SqlConnection(connetionString_SQL))
                {
                    sqlconn.Open();
                    if (sqlconn.State == ConnectionState.Open)
                    {

                        SqlCommand cmd = new SqlCommand(get_sos_orders_details, sqlconn);
                        cmd.Parameters.AddWithValue("@date_minus_one_day", formatted_date_minus_one_day);
                        cmd.Parameters.AddWithValue("@year", year);
                        cmd.Parameters.AddWithValue("@month", month);
                        cmd.Parameters.AddWithValue("@date_today", date_formatted);
                        SqlDataReader rs = cmd.ExecuteReader();
                        while (rs.Read())
                        {
                            // access your record colums by using reader

                            Console.WriteLine(rs["StoreId"]);
                            cnn.Open();
                            MySqlCommand comm = cnn.CreateCommand();
                            comm.CommandText = @"INSERT INTO master_data.so_v2 (StoreId,TransTime,Cashier,Transaction_Type,TransactionId,Cashier_Time,Preparation_Time)
                            VALUES(@Storeid, @TransTime, @Cashier, @Transaction_Type, @TransactionId, @Cashier_Time, @Preparation_Time)";
                            comm.Parameters.AddWithValue("@Storeid", rs["StoreId"]);
                            comm.Parameters.AddWithValue("@TransTime", rs["TransTime"]);
                            comm.Parameters.AddWithValue("@Cashier", rs["Cashier"]);
                            comm.Parameters.AddWithValue("@Transaction_Type", rs["Transaction_Type"]);
                            comm.Parameters.AddWithValue("@TransactionId", rs["TransactionId"]);
                            comm.Parameters.AddWithValue("@Cashier_Time", rs["Cashier_Time"]);
                            comm.Parameters.AddWithValue("@Preparation_Time", rs["Preparation_Time"]);
                            comm.ExecuteNonQuery();
                            cnn.Close();
                        }

                    }
                    sqlconn.Close();
                }
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

Thank you.

SoulAiker
  • 139
  • 1
  • 10
  • Use Sql Server Management Studio to make sure your connection information is correct. Are you able to connect to the database `10.17.27.120\sqlexpress` using those credentials from Management Studio? Also, it's **exteremely poor practice** to use the `sa` account. Ever. Make a different user with the appropriate permissions and use that. – Joel Coehoorn Nov 22 '19 at 16:56
  • 1
    A connection string is just a string nothing more. It can't determine any connection period. You need an object like `SqlConnection` to make that happen in order to communicate to the server as you already know. – Trevor Nov 22 '19 at 16:57
  • This could help: https://stackoverflow.com/questions/2440060/whats-the-best-way-to-test-sql-server-connection-programmatically – Christoph Lütjen Nov 22 '19 at 16:58
  • @JoelCoehoorn hi joel, same as same error on my studio. what error says to my message box. sorry for that, I just started practicing the mssql, but thank you for ruling me about the poor practice. – SoulAiker Nov 22 '19 at 17:00
  • @Çöđěxěŕ, Can you give example, or can you elaborate more. thank you. – SoulAiker Nov 22 '19 at 17:01
  • Don't worry about the code until you can make the connection happen from Management Studio. – Joel Coehoorn Nov 22 '19 at 17:02
  • @Çöđěxěŕ i update my sample code in my sql connection string, so to understand well, we have 100 + server name so each server name data, the data itself will insert to the mysql database. so i want to filter out if the server name is down or close. because it happens when the sql connection string is stop the inserting process is stop also . how can i filter that if the server is down then skip that counter then proceed to the next counter. – SoulAiker Nov 22 '19 at 17:09
  • @JoelCoehoorn i update my sample code in my sql connection string, so to understand well, we have 100 + server name so each server name data, the data itself will insert to the mysql database. so i want to filter out if the server name is down or close. because it happens when the sql connection string is stop the inserting process is stop also . how can i filter that if the server is down then skip that counter then proceed to the next counter – SoulAiker Nov 22 '19 at 17:10
  • You'll have to attempt to make a connection first... Also determining if a server is down is different than checking if you can connect to a database... – Trevor Nov 22 '19 at 17:11
  • can you give example @Çöđěxěŕ thank you. – SoulAiker Nov 22 '19 at 17:12
  • @Çöđěxěŕ, I'm not sure why you think his question can't be answered. – Casey Crookston Nov 22 '19 at 18:05
  • @CaseyCrookston explain `is there way to determine whether this connection string is down or not?` how to do that? How do you validate a connection string without connecting, please explain. – Trevor Nov 22 '19 at 18:06
  • @Çöđěxěŕ, see my answer below. – Casey Crookston Nov 22 '19 at 18:06
  • @Çöđěxěŕ -- also, allowances should be made for English not being someone's first language. We knew what the OP meant, even if his grammar is not perfect. Why not err on the side of being nice and helping? – Casey Crookston Nov 22 '19 at 18:08
  • `We knew what the OP meant` not entirely, read the comments as well; here's one case `i want to filter out if the server name is down or close. because it happens when the sql connection string is stop the inserting process is stop also . how can i filter that if the server is down`, now does the OP mean the server or connection to a db?... – Trevor Nov 22 '19 at 18:11
  • @SoulAiker did you check out the link by Christoph Lütjen? – Trevor Nov 22 '19 at 18:13
  • @Çöđěxěŕ, reading between the lines, it seemed to me like what OP was asking is this: "If I try and use a given connection string, will it work? Or will it throw an error?". I agree that he didn't seem to know how to properly phrase the question. But again, I think we generally knew what he was trying to say. If I'm wrong, he can tell me. – Casey Crookston Nov 22 '19 at 18:15
  • Sorry guys, Thank you everything. solve the problem, I forgot to add exception, thanks everyone for commenting. have a nice day. – SoulAiker Nov 22 '19 at 18:32

1 Answers1

0

I suppose if all you wanted was a way to test and make sure a connection string is valid and that you can connect to the server and to the database, you could use a method like this:

public bool IsConnectionStringValid(string cs)
{
    try
    {
         using (MySqlConnection conn = new MySqlConnection(cs))
         {
             conn.Open();
             return true;
         }
    }
    catch
    {
        return false;
    }
}

Although I have to admit, in all my years of developing in C#, I've never used anything like this. Normally, as people have said in the comments, you already know before runtime that your connection string is valid and working.

Casey Crookston
  • 13,016
  • 24
  • 107
  • 193