Monday, March 6, 2023

CONNECT TO AN EXTERNAL SQL DATABASE USING X++

 CONNECT TO AN EXTERNAL SQL DATABASE USING X++.


using System.Data.SqlClient;
class sQLConnect
{
    public static void main(Args _args)
    {
        System.Exception            ex;

	//Fetching
        SqlConnection conn = new SqlConnection("Server='IP adress'; Database='Database name'; 
                            User Id='Id'; Password='Password'; Min Pool Size = 5; Max Pool Size=100;");
      
        str myField= 'Test123';
        
        str sqlL = strFmt("Select field1,format(DATEANDTIME,'dd/MM/yyyy HH:mm:ss') as DATEANDTIME,
                    field2  FROM MyTble WHERE MyTble.field1 = '" + myField + "' and MyTble.isTrue = 1");
      
        SqlCommand      command = new SqlCommand(sqlL, conn);

        System.Data.SqlClient.SqlDataReader reader;
        System.Data.SqlClient.SqlParameterCollection parameterCollection;
        new InteropPermission(InteropKind::ClrInterop ).assert();

        try
        {
            conn.Open();
            try
            {
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Info(reader.get_Item('field1'));
                    Info(reader.get_Item('DATEANDTIME'));
                    Info(reader.get_Item('field2'));
                }
                reader.Dispose();
            }
            catch
            {
                reader.Dispose();
            }
        }
        catch
        {
            ex = CLRInterop::getLastException().GetBaseException();
            error(ex.get_Message());
        }

	--------------------------------------------------------------------------------------
		
        System.Exception            ex;

        //Inserting
	SqlConnection conn = new SqlConnection("Server='IP adress'; Database='Database name'; 
                        User Id='Id'; Password='Password'; Min Pool Size = 5; Max Pool Size=100;");
        try
        {
           
            str insert = "INSERT INTO [MyTble](field1,DATEANDTIME,field2) VALUES";

	    insert = insert + "('"+field1+"','"+DATEANDTIME+"','"+field2+"')";

            SqlCommand insCmd = new SqlCommand(insert, conn);

            conn.Open();
			
	    // for update
            //update="UPDATE MyTble SET field2 = '" + newvalue + "' WHERE field1 = '" + field1 + "'";
            //updateCmd.CommandText=update;
            insCmd.ExecuteNonQuery();
        }
        catch
        {
            ex = CLRInterop::getLastException().GetBaseException();
            error(ex.get_Message());
        }
    }

}


Ref : Link

Keep Daxing!!

No comments:

Post a Comment